"use client";

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

export default function ChatMessages({ consultationId }) {
    const { socket, isConnected } = useSocket();
    const [messages, setMessages] = useState([]);
    const [newMessage, setNewMessage] = useState('');
    const [conversation, setConversation] = useState(null);
    const messagesEndRef = useRef(null);

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

    const user = userData?.profile || null;

    useEffect(() => {
        const fetchMessages = async () => {

            try {
                const [conversationRes, messagesRes] = await Promise.all([
                    fetch(`/api/consultations/${consultationId}`, { credentials: 'include' }),
                    fetch(`/api/consultations/${consultationId}/messages`, { credentials: 'include' })
                ]);
                if (!conversationRes.ok || !messagesRes.ok) {
                    throw new Error('Failed to load conversation');
                }

                const [conversationData, messagesData] = await Promise.all([
                    conversationRes.json(),
                    messagesRes.json()
                ]);
                setConversation(conversationData);
                setMessages(messagesData);
            } catch (err) {
                console.error('Error loading messages', err);
            }
        };

        fetchMessages();

        if (!socket) return;

        socket.emit('join-consultation', consultationId);

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

        socket.on('new-message', handleNewMessage);

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

    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    const sendMessage = () => {
        if (!newMessage.trim()) return;

        const message = {
            content: newMessage,
            senderId: user.userId,
            consultationId
        };

        socket.emit('send-message', message, (response) => {
            if (response.error) {
                console.error('Error sending message:', response.error);
            }
        });

        setNewMessage('');
    };

    if (!conversation) {
        return <div className="flex-1 flex items-center justify-center">Loading...</div>;
    }

    const otherUser = conversation.patientId === user.userId
        ? conversation.doctor
        : conversation.patient;

    const isDoctor = otherUser.role === 'doctor';

    const profile = isDoctor ? otherUser.doctorProfile
        : otherUser.patientProfile;

    return (
        <div className="flex-1 flex flex-col">
            <div className="border-b p-4 flex items-center">
                <div className="flex-shrink-0 h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                    <span className="text-gray-600">
                        {profile.firstName.charAt(0)}
                        {profile.lastName.charAt(0)}
                    </span>
                </div>
                <div className="ml-3">
                    <h2 className="text-lg font-semibold">
                        {isDoctor ? 'Dr.' : ''} {profile.firstName} {profile.lastName}
                    </h2>
                    <p className="text-sm text-gray-500">{profile.specialization}</p>
                </div>
            </div>

            <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50">
                {messages.map((message) => (
                    <div
                        key={message.createdAt}
                        className={`flex ${message.senderId === user.userId ? 'justify-end' : 'justify-start'}`}
                    >
                        <div
                            className={`max-w-xs md:max-w-md rounded-lg p-3 ${message.senderId === user.userId
                                ? 'bg-blue-500 text-white'
                                : 'bg-gray-800'
                                }`}
                        >
                            <p>{message.content}</p>
                            <p className="text-xs mt-1 opacity-70">
                                {new Date(message.createdAt).toLocaleTimeString([], {
                                    hour: '2-digit',
                                    minute: '2-digit'
                                })}
                            </p>
                        </div>
                    </div>
                ))}
                <div ref={messagesEndRef} />
            </div>

            <div className="border-t p-4 bg-white">
                <div className="flex gap-2">
                    <input
                        id="messageInput"
                        type="text"
                        className="flex-1 border rounded-lg p-2 focus:outline-none focus:ring-2 focus:ring-blue-500 text-stone-950"
                        value={newMessage}
                        onChange={(e) => setNewMessage(e.target.value)}
                        onKeyDown={(e) => e.key === 'Enter' && sendMessage()}
                        placeholder="Type your message..."
                    />
                    <button
                        onClick={sendMessage}
                        disabled={!isConnected || !newMessage.trim()}
                        className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 disabled:bg-gray-400 transition-colors"
                    >
                        Send
                    </button>
                </div>
            </div>
        </div>
    );
}