"use client";

import { useEffect, useState, useRef } from 'react';
import { useSocket } from '@/context/SocketContext';
import { useParams } from 'next/navigation';
import { useAuthStore } from '@/stores/authStore';

export default function ChatPage() {
    const { consultationId } = useParams();
    const { socket, isConnected } = useSocket();
    const [messages, setMessages] = useState([]);
    const [newMsg, setNewMsg] = useState('');
    const bottomRef = useRef(null);

    const userData = useAuthStore((state) => state.user);

    const user = userData?.profile || null;

    const fetchMessages = async () => {
        const url = `/api/consultations/${consultationId}/messages`;

        try {
            const res = await fetch(url);
            const data = await res.json();
            setMessages(data);
        } catch (err) {
            console.error('Error loading messages', err);
        }
    };

    useEffect(() => {
        fetchMessages();

        if (!socket) return;

        socket.emit('join-room', consultationId); // optional: join room per consultation

        socket.on('message:receive', (message) => {
            setMessages((prev) => [...prev, message]);
        });

        return () => {
            socket.off('message:receive');
        };
    }, [socket, consultationId]);

    // Set up socket listeners
    useEffect(() => {
        if (!socket || !consultationId) return;

        const handleNewMessage = (message) => {
            if (message.consultationId === consultationId) {
                setMessages(prev => [...prev, message]);
            }
        };

        socket.on('new_message', handleNewMessage);

        return () => {
            socket.off('new_message', handleNewMessage);
        };
    }, [socket, consultationId]);

    // Auto-scroll to bottom when new messages arrive
    useEffect(() => {
        bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    const handleSend = () => {
        if (!newMsg.trim()) return;

        const message = {
            content: newMsg,
            consultationId
        };

        socket.emit('send_message', message);
        setMessages((prev) => [...prev, { ...message, createdAt: new Date() }]);
        setNewMsg('');
    };

    return (
        <div className="flex flex-col h-screen p-4">
            <h2 className="text-xl font-bold mb-2">Chat with Doctor</h2>

            <div className="flex-1 overflow-y-auto space-y-2">
                {messages.map((msg, idx) => {
                    const isSender = msg.senderId === user.userId;
                    return (
                        <div
                            key={idx}
                            className={`max-w-xs px-4 py-2 rounded-lg text-white ${isSender ? 'bg-blue-600 self-end ml-auto' : 'bg-gray-300 text-black self-start mr-auto'
                                }`}
                        >
                            {msg.content}
                        </div>
                    );
                })}
                <div ref={bottomRef}></div>
            </div>

            <div className="flex mt-4 gap-2">
                <input
                    type="text"
                    value={newMsg}
                    onChange={(e) => setNewMsg(e.target.value)}
                    placeholder="Type your message"
                    className="flex-1 border rounded px-3 py-2"
                />
                <button onClick={handleSend} className="bg-blue-600 text-white px-4 py-2 rounded">
                    Send
                </button>
            </div>
        </div>
    );
}
