'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { Eye, MessageCircle, Share2 } from 'lucide-react';
import PatientModal from './PatientModal';
import MessagesModal from '../chat/MessagesModal';
import ReferModal from './ReferModal';
import { useAuthStore } from '@/stores/authStore';
import { useSocket } from '@/context/SocketContext';

export default function PatientList() {
  const user = useAuthStore((state) => state.user);
  const { socket } = useSocket();
  const router = useRouter();

  const [patients, setPatients] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedPatient, setSelectedPatient] = useState(null);
  const [messagingPatient, setMessagingPatient] = useState(null);
  const [referPatient, setReferPatient] = useState(null);

  useEffect(() => {
    const fetchPatients = async () => {
      if (!user?.id) return;
      try {
        const res = await fetch(`/api/patients?doctorId=${user.id}`, {
          credentials: 'include',
        });
        if (!res.ok) throw new Error('Failed to fetch patients');
        setPatients(await res.json());
      } catch (err) {
        console.error('Error:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchPatients();
  }, [user]);

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

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

      {patients.length === 0 ? (
        <div className="py-20 text-center text-gray-600 bg-gray-50 rounded-xl">
          <Eye className="w-16 h-16 mx-auto text-gray-400 mb-4" />
          <p>No patients have been assigned yet.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
          {patients.map((patient) => (
            <div
              key={patient.id}
              className="bg-white shadow-md rounded-xl p-4 flex flex-col justify-between"
            >
              <div className="relative w-full h-32 rounded-lg overflow-hidden bg-indigo-200 mb-4" />
              <div className="flex items-center -mt-12 justify-center">
                <img
                  src={
                    patient.avatar
                      ? patient.avatar
                      : '/images/patient1.jpg'
                  }
                  alt={`${patient.firstName} ${patient.lastName}`}
                  width={80}
                  height={80}
                  className="rounded-full border-4 border-white shadow-md object-cover z-50"
                />
              </div>
              <h3 className="text-lg font-bold text-center mt-2">
                {patient.firstName} {patient.middleName} {patient.lastName}
              </h3>
              <p className="text-center text-sm text-gray-500">{patient.email}</p>
              <div className="mt-2 text-sm text-gray-700 space-y-1">
                <p>
                  <strong>Gender:</strong> {patient.gender}
                </p>
                <p>
                  <strong>Phone:</strong> {patient.phone}
                </p>
              </div>

              <div className="mt-4 flex justify-around">
                <button
                  onClick={() => setSelectedPatient(patient)}
                  className="p-2 bg-indigo-100 rounded-full hover:bg-indigo-200"
                >
                  <Eye className="w-5 h-5 text-indigo-600" />
                </button>
                <button
                  onClick={() => setMessagingPatient(patient)}
                  className="p-2 bg-green-100 rounded-full hover:bg-green-200"
                >
                  <MessageCircle className="w-5 h-5 text-green-600" />
                </button>
                <button
                  onClick={() => setReferPatient(patient)}
                  className="p-2 bg-yellow-100 rounded-full hover:bg-yellow-200"
                >
                  <Share2 className="w-5 h-5 text-yellow-600" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {selectedPatient && (
        <PatientModal patient={selectedPatient} onClose={() => setSelectedPatient(null)} />
      )}
      {messagingPatient && (
        <MessagesModal recipient={messagingPatient} onClose={() => setMessagingPatient(null)} />
      )}
      {referPatient && (
        <ReferModal patient={referPatient} onClose={() => setReferPatient(null)} />
      )}
    </div>
  );
}
