'use client';

import { useTranslations } from 'next-intl';
import { Search } from 'lucide-react';
import { Input } from '@/components/ui/shared/Input';
import { formatMobileForDisplay } from '@/lib/phone';
import { Patient } from '@/types/patient';

interface PatientSearchSelectProps {
  search: string;
  onSearchChange: (value: string) => void;
  patients: Patient[];
  selectedPatientId?: string;
  onSelectPatient: (patient: Patient) => void;
  loading?: boolean;
}

export function PatientSearchSelect({
  search,
  onSearchChange,
  patients,
  selectedPatientId,
  onSelectPatient,
  loading = false,
}: PatientSearchSelectProps) {
  const t = useTranslations('patients');

  return (
    <div className="surface-card p-4 space-y-4">
      <Input
        placeholder={t('searchPlaceholder')}
        value={search}
        onChange={(e) => onSearchChange(e.target.value)}
        icon={<Search className="h-4 w-4 icon-flat" />}
      />

      <div className="space-y-2 max-h-80 overflow-y-auto">
        {loading && <p className="text-sm text-text-muted">{t('loadingPatients')}</p>}

        {!loading && patients.length === 0 && (
          <p className="text-sm text-text-muted">{t('noResults')}</p>
        )}

        {patients.map((patient) => {
          const isSelected = selectedPatientId === patient.id;
          return (
            <button
              key={patient.id}
              type="button"
              onClick={() => onSelectPatient(patient)}
              className={`w-full text-left rounded-[var(--radius-sm)] border px-3 py-2 transition-colors ${
                isSelected
                  ? 'bg-primary-soft border-primary/60'
                  : 'border-border/60 hover:bg-background-card/70'
              }`}
            >
              <p className="text-sm font-medium text-text-primary">
                {patient.firstName} {patient.lastName}
              </p>
              <p className="text-xs text-text-muted">
                {formatMobileForDisplay(patient.mobile) || patient.email || t('noContact')}
              </p>
            </button>
          );
        })}
      </div>
    </div>
  );
}
