'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import ChatWindow from './ChatWindowModal';
import { useSocket } from '@/context/SocketContext';
import { useAuthStore } from '@/stores/authStore';
import { MessageCircleOff } from 'lucide-react';

export default function MessagesModal({ recipient = null, onClose }) {
  const { socket } = useSocket();
  const user = useAuthStore((state) => state.user?.profile || null);
  const [conversations, setConversations] = useState([]);
  const [selectedChat, setSelectedChat] = useState(null);
  const [creatingChat, setCreatingChat] = useState(false);

  const hasStartedChatRef = useRef(false);

  const handleStartNewChat = useCallback(async (doctor) => {
    if (creatingChat || !user) return;
    setCreatingChat(true);

    try {
      const res = await fetch('/api/consultations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          issue: 'New consultation',
          patientId: user.userId,
          doctorId: doctor.userId,
          type: 'text',
        }),
      });

      if (!res.ok) throw new Error('Failed to create conversation');
      const newConv = await res.json();

      setConversations((prev) => [...prev, newConv.consultation]);
      setSelectedChat(newConv.consultation);

      socket?.emit('new_conversation', newConv.consultation);
    } catch (err) {
      console.error('Error creating conversation:', err);
    } finally {
      setCreatingChat(false);
    }
  }, [creatingChat, user, socket]);

  useEffect(() => {
    const fetchConversations = async () => {
      try {
        const res = await fetch('/api/consultations');
        if (!res.ok) throw new Error('Failed to fetch conversations');
        const data = await res.json();
        setConversations(data);

        if (recipient && user && !hasStartedChatRef.current) {
          const existing = data.find(
            conv =>
              (conv.doctorId === recipient.userId && conv.patientId === user.userId) ||
              (conv.patientId === recipient.userId && conv.doctorId === user.userId)
          );

          if (existing) {
            setSelectedChat(existing);
          } else {
            hasStartedChatRef.current = true;
            await handleStartNewChat(recipient);
          }
        }
      } catch (error) {
        console.error('Error loading conversations:', error);
      }
    };

    fetchConversations();
  }, [recipient, user, handleStartNewChat]);

  useEffect(() => {
    if (!socket) return;

    const handleNewConversation = (conversation) => {
      setConversations(prev => {
        const exists = prev.find(conv => conv.id === conversation.id);
        return exists ? prev : [...prev, conversation];
      });
    };

    socket.on('new_conversation', handleNewConversation);
    return () => socket.off('new_conversation', handleNewConversation);
  }, [socket]);

  return (
    <div className="fixed inset-0 bg-white/30 backdrop-blur-sm flex items-center justify-center z-50 px-4">
      <div className="bg-white rounded-xl w-full max-w-5xl h-[90vh] flex overflow-hidden shadow-lg relative">
        {selectedChat ? (
          <ChatWindow conversation={selectedChat} goBack={() => setSelectedChat(null)} />
        ) : (
          <div className="flex flex-col items-center justify-center w-full text-gray-500">
            <MessageCircleOff className="w-12 h-12 mb-3 opacity-50" />
            <p className="text-md font-semibold">No conversation selected</p>
            <p className="text-sm text-gray-400 px-4 text-center">
              Select or start a chat to begin messaging.
            </p>
          </div>
        )}

        <button
          onClick={onClose}
          className="absolute top-2 right-2 text-gray-600 hover:text-black text-xl font-bold"
        >
          ×
        </button>
      </div>
    </div>
  );
}
