'use client';

import { useEffect, useState } from 'react';
import Image from 'next/image';
import { MessageSquareOff } from 'lucide-react';
import ConsultationMessageModal from '../chat/ConsultationMessageModal';
import PatientList from './PatientList';

export default function GeneralConsultationList({ onSelect, currentDoctorId }) {
  const [consultations, setConsultations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedConsultation, setSelectedConsultation] = useState(null);

  useEffect(() => {
    const fetchGeneralConsultations = async () => {
      try {
        const res = await fetch('/api/generalconsultations');
        const data = await res.json();
        console.log('Fetched consultations:', data);
        setConsultations(data.consultations || []);
      } catch (error) {
        console.error('Error fetching consultations:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchGeneralConsultations();
  }, []);

  const handleSelect = (consultation) => {
    setSelectedConsultation(consultation);
    onSelect?.(consultation); // Optional
  };

  return (
    <div className="bg-white p-4 rounded-xl shadow-lg space-y-4">
      <h3 className="text-2xl font-semibold text-gray-800">General Consultations</h3>

      {loading ? (
        <p className="text-gray-500 text-sm">Loading consultations...</p>
      ) : consultations.length === 0 ? (
        <div className="flex flex-col items-center justify-center text-center text-gray-600 py-16 rounded-lg bg-gray-50 border border-dashed border-gray-300">
          <MessageSquareOff className="w-12 h-12 mb-3 text-gray-400" />
          <p className="text-lg font-semibold">No consultations found</p>
          <p className="text-sm text-gray-500 mt-1">You&apos;re all caught up — new consultations will appear here.</p>
        </div>
      ) : (
        <ul className="divide-y divide-gray-200">
          {consultations.map((consultation) => {
            const profile = consultation.patient?.patientProfile || {};
            const latestMessage = consultation.messages?.[0];
            const altText = `${profile.firstName || 'Patient'}’s avatar`; // ✅ Escaped using typographic apostrophe

            return (
              <li
                key={consultation.id}
                className="py-4 px-2 cursor-pointer hover:bg-gray-50 transition rounded-md"
                onClick={() => handleSelect(consultation)}
              >
                <div className="flex items-center gap-4">
                  <div className="flex-shrink-0">
                    <img
                    width={48}
                      height={48}
                      src={
                        profile.avatar
                          ? profile.avatar
                          : '/images/patient1.jpg'
                      }
                      alt={altText}
                      className="rounded-full border-4 border-white shadow-md object-cover z-50"
                    />
                  </div>

                  <div className="flex-1 min-w-0">
                    <p className="font-semibold text-gray-800 truncate">
                      {profile.firstName || 'Unnamed'} {profile.lastName || ''}
                    </p>
                    <p className="text-sm text-gray-500 truncate">{consultation.patient?.email || 'No email provided'}</p>
                    {latestMessage && (
                      <p className="text-xs text-gray-400 mt-1 italic truncate">
                        &quot;{latestMessage.content}&quot; – {new Date(latestMessage.createdAt).toLocaleString()}
                      </p>
                    )}
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      )}

      {selectedConsultation && currentDoctorId && (
        <ConsultationMessageModal
          consultation={selectedConsultation}
          currentDoctorId={currentDoctorId}
          onClose={() => setSelectedConsultation(null)}
        />
      )}
      <PatientList />
    </div>
  );
}
