'use client';

import { useEffect, useState } from 'react';
import { listPatients } from '@/lib/services/patients';
import type { Patient } from '@/lib/types';
import { formatCpf } from '@/components/app/ui';

/** Busca de paciente por nome/CPF com seleção. */
export default function PatientSelect({
  id,
  value,
  onChange,
  invalid,
}: {
  id: string;
  value: number | '';
  onChange: (patientId: number | '') => void;
  invalid?: boolean;
}) {
  const [search, setSearch] = useState('');
  const [options, setOptions] = useState<Patient[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let active = true;
    const timer = setTimeout(async () => {
      setLoading(true);
      try {
        const page = await listPatients({ search: search.trim() || undefined, limit: 20 });
        if (active) setOptions(page.data);
      } catch {
        if (active) setOptions([]);
      } finally {
        if (active) setLoading(false);
      }
    }, 300);
    return () => {
      active = false;
      clearTimeout(timer);
    };
  }, [search]);

  return (
    <div className="d-flex flex-column gap-2">
      <input
        className="form-control"
        placeholder="Buscar por nome ou CPF"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        aria-label="Buscar paciente"
      />
      <select
        id={id}
        className={`form-select ${invalid ? 'is-invalid' : ''}`}
        value={value}
        onChange={(e) => onChange(e.target.value ? Number(e.target.value) : '')}
      >
        <option value="">{loading ? 'Buscando…' : 'Selecione o paciente'}</option>
        {options.map((patient) => (
          <option key={patient.id} value={patient.id}>
            {patient.fullName}
            {patient.cpf ? ` — ${formatCpf(patient.cpf)}` : ''}
          </option>
        ))}
      </select>
    </div>
  );
}
