'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import DoctorProfileModal from './DoctorModal';
import AppointmentModal from './AppointmentModal';
import MessagesModal from '../chat/MessagesModal';

import { Eye, CalendarCheck, MessageCircle } from 'lucide-react';

export default function DoctorList() {
    const [doctors, setDoctors] = useState([]);
    const [loading, setLoading] = useState(true);
    const [selectedDoctor, setSelectedDoctor] = useState(null);
    const [bookingDoctor, setBookingDoctor] = useState(null);
    const [messagingDoctor, setMessagingDoctor] = useState(null);

    useEffect(() => {
        const fetchDoctors = async () => {
            try {
                const res = await fetch('/api/doctors');
                if (!res.ok) throw new Error('Failed to fetch doctors');
                const data = await res.json();
                setDoctors(data);
            } catch (error) {
                console.error('Error fetching doctors:', error.message);
            } finally {
                setLoading(false);
            }
        };

        fetchDoctors();
    }, []);

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

    return (
        <div className="space-y-4 p-4">
            <h1 className="text-2xl font-semibold">Doctor List</h1>

            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
                {doctors.map((doctor) => (
                    <div
                        key={doctor.id}
                        className="bg-white shadow-md rounded-xl p-4 flex flex-col justify-between hover:shadow-lg transition-shadow duration-300"
                    >
                        <div className="relative w-full h-32 rounded-lg overflow-hidden mb-4 bg-indigo-200"></div>

                        <div className="flex items-center -mt-12 justify-center">
                            <img
                                src={
                                    doctor?.avatar
                                        ? doctor.avatar
                                        : '/images/patient2.jpg'
                                }
                                alt={`${doctor?.firstName || ''} ${doctor?.lastName || ''}`}
                                width={80}
                                height={80}
                                className="rounded-full border-4 border-white shadow-md z-50 object-cover"
                            />
                        </div>

                        <h3 className="text-lg font-bold text-center mt-2">
                            Dr. {doctor.firstName} {doctor.lastName}
                        </h3>
                        <p className="text-center text-sm text-gray-500">{doctor.specialization}</p>
                        <p className="text-sm mt-2 text-gray-600 line-clamp-3">{doctor.bio}</p>

                        <div className="flex justify-around mt-4">
                            <button
                                onClick={() => setSelectedDoctor(doctor)}
                                className="p-2 bg-indigo-100 hover:bg-indigo-200 rounded-full transition"
                                aria-label="View Profile"
                                title="View Profile"
                            >
                                <Eye className="w-5 h-5 text-indigo-600" />
                            </button>

                            <button
                                onClick={() => setBookingDoctor(doctor)}
                                className="p-2 bg-purple-100 hover:bg-purple-200 rounded-full transition"
                                aria-label="Book Appointment"
                                title="Book Appointment"
                            >
                                <CalendarCheck className="w-5 h-5 text-purple-600" />
                            </button>

                            <button
                                onClick={() => setMessagingDoctor(doctor)}
                                // fix when null to do!!!
                                className="p-2 bg-green-100 hover:bg-green-200 rounded-full transition"
                                aria-label="Message Doctor"
                                title="Message Doctor"
                            >
                                <MessageCircle className="w-5 h-5 text-green-600" />
                            </button>
                        </div>
                    </div>
                ))}
            </div>

            {/* Modals */}
            {selectedDoctor && (
                <DoctorProfileModal doctor={selectedDoctor} onClose={() => setSelectedDoctor(null)} />
            )}
            {bookingDoctor && (
                <AppointmentModal
                    doctor={bookingDoctor}
                    onClose={() => setBookingDoctor(null)}
                    onSuccess={() => {
                        setBookingDoctor(null);
                        setTimeout(() => {
                            router.push('/dashboard/patient/appointments');
                        }, 200);
                    }}
                />
            )}

            {messagingDoctor && (
                <MessagesModal recipient={messagingDoctor} onClose={() => setMessagingDoctor(null)} />
            )}
        </div>
    );
}
