'use client';

import { useEffect, useState } from 'react';

export default function ConsultationHistoryList({ selectedPatient, onSelectConsultation }) {
  const [consultations, setConsultations] = useState([]);

  useEffect(() => {
    if (!selectedPatient) return;
    // Fetch consultations based on selectedPatient
    const fetchConsultations = async () => {
      try {
        const res = await fetch(`/api/consultations?patientId=${selectedPatient}`);
        const data = await res.json();
        setConsultations(data);
      } catch (error) {
        console.error('Failed to fetch consultations:', error);
      }
    };

    fetchConsultations();
  }, [selectedPatient]);

  return (
    <div className="bg-white p-4 rounded shadow">
      <h2 className="text-lg font-semibold mb-2">Consultation History</h2>
      {consultations.length === 0 ? (
        <p>No previous consultations found.</p>
      ) : (
        <ul className="divide-y divide-gray-200">
          {consultations.map((consultation) => (
            <li
              key={consultation.id}
              className="py-2 cursor-pointer hover:bg-gray-100"
              onClick={() => onSelectConsultation(consultation)}
            >
              <div className="font-medium">{consultation.title || 'Consultation'}</div>
              <div className="text-sm text-gray-500">{new Date(consultation.date).toLocaleString()}</div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
