'use client';

import { useState, useEffect } from 'react';

export default function PatientSelection({ selectedPatient, setSelectedPatient }) {
  const [patientList, setPatientList] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchPatients = async () => {
      try {
        const res = await fetch('/api/patients');
        if (!res.ok) throw new Error('Failed to fetch patients');
        const data = await res.json();
        setPatientList(data);
      } catch (error) {
        console.error('Error loading patients:', error);
        setPatientList([]);
      } finally {
        setLoading(false);
      }
    };

    fetchPatients();
  }, []);

  const handleSelectionChange = (e) => {
    const selectedId = e.target.value;
    const patient = patientList.find((p) => p.id === selectedId);
    setSelectedPatient(patient);
  };

  return (
    <div className="bg-white p-4 rounded shadow-md">
      <h2 className="text-lg font-semibold mb-4">Select a Patient</h2>

      {loading ? (
        <p className="text-gray-600">Loading patients...</p>
      ) : patientList.length === 0 ? (
        <p className="text-gray-600">No patients assigned or available for consultation.</p>
      ) : (
        <select
          onChange={handleSelectionChange}
          value={selectedPatient?.id || ''}
          className="w-full p-2 border rounded text-gray-800"
        >
          <option value="" disabled>Select a patient</option>
          {patientList.map((patient) => (
            <option key={patient.id} value={patient.id}>
              {patient.name} — {patient.age} yrs
            </option>
          ))}
        </select>
      )}
    </div>
  );
}
