'use client';

import { useState, useEffect } from 'react';
import ChatWindow from './ChatWindow';
import { useSocket } from '@/context/SocketContext';
import { useAuthStore } from '@/stores/authStore';
import Image from 'next/image';
import { MessageCircleOff } from 'lucide-react';

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

  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);
      } catch (error) {
        console.error(error);
      }
    };

    fetchConversations();

    if (socket) {
      const handleNewConversation = (conversation) => {
        setConversations((prev) => [...prev, conversation]);
      };

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

  const getOtherUser = (conversation) => {
    const other = conversation.patientId === user?.userId
      ? conversation.doctor
      : conversation.patient;

    if (!other) {
      return {
        name: 'General Consultation',
        avatar: '/images/patient2.jpg',
      };
    }

    const profile = other?.role === 'doctor'
      ? other?.doctorProfile
      : other?.patientProfile;

    return {
      name: `${other?.role === 'doctor' ? 'Dr. ' : ''}${profile?.firstName || 'Unknown'} ${profile?.lastName || ''}`.trim(),
      avatar: profile?.avatar || '/images/patient2.jpg',
    };
  };

  return (
    <div className="bg-white shadow rounded-xl p-4">
      <div className="bg-white rounded-xl w-full max-w-5xl h-[90vh] flex overflow-hidden shadow-lg relative">
        {!selectedChat ? (
          <div className="p-2 overflow-y-auto w-full">
            <h2 className="text-xl font-semibold mb-4">Messages</h2>

            {conversations.length === 0 ? (
              <div className="flex flex-col items-center justify-center mt-24 text-gray-500">
                <MessageCircleOff className="w-12 h-12 mb-3 opacity-50" />
                <p className="text-md font-semibold">No conversations yet</p>
                <p className="text-sm text-gray-400 px-4 text-center">
                  Start a conversation to see messages here.
                </p>
              </div>
            ) : (
              conversations.map((conv) => {
                const { name, avatar } = getOtherUser(conv);
                const lastMessage = conv.messages?.[0];

                return (
                  <div
                    key={conv.id}
                    className="flex items-center gap-4 p-2 rounded-lg hover:bg-gray-300 bg-indigo-100 m-1 cursor-pointer"
                    onClick={() => setSelectedChat(conv)}
                  >
                    <img
                      width={48}
                      height={48}
                      src={avatar ? avatar : '/images/patient2.jpg'}
                      alt={name || 'Profile avatar'}
                      className="rounded-full border-4 border-white shadow-md object-cover z-50"
                    />

                    <div className="flex-1">
                      <h3 className="font-semibold">{name}</h3>
                      <p className="text-sm text-gray-500 truncate">
                        {lastMessage?.content || 'No messages yet'}
                      </p>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        ) : (
          <ChatWindow
            conversation={selectedChat}
            goBack={() => setSelectedChat(null)}
          />
        )}
      </div>
    </div>
  );
}
