"use client";

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


export default function ConsultationList() {
    const { socket } = useSocket();
    const [conversations, setConversations] = useState([]);
    const [loading, setLoading] = useState(true);
    const pathname = usePathname();

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

    const user = userData?.profile || null;

    useEffect(() => {
        const fetchConversations = async () => {
            try {
                const response = await fetch('/api/consultations');
                if (!response.ok) throw new Error('Failed to fetch conversations');
                const data = await response.json();
                setConversations(data);
            } catch (error) {
                console.error('Error loading conversations:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchConversations();

        // Set up socket listener for new conversations
        if (socket) {
            const handleNewConversation = (conversation) => {
                setConversations(prev => [...prev, conversation]);
            };

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

    if (loading) {
        return <div className="p-4">Loading conversations...</div>;
    }

    return (
        <div className="h-full overflow-y-auto">
            {conversations.length === 0 ? (
                <div className="p-4 text-gray-500">No conversations yet</div>
            ) : (
                <ul className="divide-y divide-gray-200">
                    {conversations.map((conversation) => {
                        const otherUser = conversation.patientId === user.userId
                            ? conversation.doctor
                            : conversation.patient;
                        const isDoctor = otherUser.role === 'doctor';

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

                        const isActive = pathname.includes(`/chat/${conversation.id}`);

                        return (
                            <li key={conversation.id}>
                                <Link
                                    href={`/chat/${conversation.id}`}
                                    className={`block p-4 hover:bg-gray-50 transition-colors ${isActive ? 'bg-blue-50 border-l-4 border-blue-500' : ''
                                        }`}
                                >
                                    <div className="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">
                                            <p className="text-sm font-medium text-gray-900">
                                                {isDoctor ? 'Dr.' : ''} {profile.firstName} {profile.lastName}
                                            </p>
                                            <p className="text-sm text-gray-500 truncate max-w-xs">
                                                {conversation.messages[0]?.content || 'No messages yet'}
                                            </p>
                                        </div>
                                        {conversation.unreadCount > 0 && (
                                            <span className="ml-auto bg-blue-500 text-white text-xs font-bold px-2 py-1 rounded-full">
                                                {conversation.unreadCount}
                                            </span>
                                        )}
                                    </div>
                                </Link>
                            </li>
                        );
                    })}
                </ul>
            )}
        </div>
    );
}