"use client";

import { useState, useEffect } from 'react';
import { useSocket } from '@/context/SocketContext';
import { useRouter } from 'next/navigation';
import axios from 'axios';
// import { useAuth } from '@/hooks/useAuth';
import { useAuthStore } from '@/stores/authStore';

export default function DoctorsList() {
    const [doctors, setDoctors] = useState([]);
    const router = useRouter();
    const [loadingConversations, setLoadingConversations] = useState({});

    useEffect(() => {

        const fetchDoctors = async () => {
            try {
                const res = await fetch("/api/doctors", {
                    method: "GET",
                    credentials: "include",
                });
                const data = await res.json();
                setDoctors(data);
            } catch (err) {
                console.error('Failed to fetch doctors:', err);
            }
        };
        fetchDoctors();
    }, []);

    const startChat = async (doctorId) => {
        try {
            setLoadingConversations(prev => ({ ...prev, [doctorId]: true }));

            const response = await fetch('/api/consultations', {
                method: 'POST',
                body: JSON.stringify({ doctorId, type: "text" })
            });

            if (!response.ok) throw new Error('Failed to start conversation');

            const conversation = await response.json();

            // Navigate to the chat page
            router.push(`/consultation/chat/${conversation.id}`);
        } catch (error) {
            console.error('Error starting chat:', error);
            alert('Failed to start conversation');
        } finally {
            setLoadingConversations(prev => ({ ...prev, [doctorId]: false }));
        }
    };

    return (
        <div className="space-y-4">
            {doctors.map(doctor => (
                <div key={doctor.id} className="p-4 border rounded-lg flex justify-between items-center">
                    <div>
                        <h3 className="font-semibold">{doctor.firstName} {doctor.lastName}</h3>
                        <p className="text-sm text-gray-600">{doctor.specialization}</p>
                    </div>
                    <button
                        onClick={() => startChat(doctor.User.id)}
                        disabled={loadingConversations[doctor.id]}
                        className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 disabled:bg-blue-300"
                    >
                        {loadingConversations[doctor.id] ? 'Starting...' : 'Start Chat'}
                    </button>
                </div>
            ))}
        </div>
    );
}