'use client';

import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/shared/Button';
import { PatientSearchCombobox } from '@/components/ui/patient/PatientSearchCombobox';
import { usePatientSearchQuery } from '@/lib/hooks/usePatientSearchQuery';
import type { Patient } from '@/types/patient';

interface NewTreatmentPatientPickerProps {
  creating?: boolean;
  onSelectWalkIn: () => void | Promise<void>;
  onSelectPatient: (patient: Patient) => void | Promise<void>;
  onCancel: () => void;
}

export function NewTreatmentPatientPicker({
  creating = false,
  onSelectWalkIn,
  onSelectPatient,
  onCancel,
}: NewTreatmentPatientPickerProps) {
  const t = useTranslations('treatment');
  const tCommon = useTranslations('common');
  const tPatients = useTranslations('patients');
  const { search, setSearch, patients, loading } = usePatientSearchQuery(!creating);

  return (
    <div className="space-y-3 rounded-[var(--radius-md)] border border-border/70 bg-background-secondary/40 p-3">
      <p className="text-sm font-medium text-text-primary">{t('newTreatmentPatientPrompt')}</p>
      <button
        type="button"
        disabled={creating}
        onClick={() => void onSelectWalkIn()}
        className="w-full rounded-[var(--radius-md)] border border-primary/40 bg-primary-soft px-3 py-2 text-start transition-colors hover:border-primary disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/45"
      >
        <p className="text-sm font-medium text-text-primary">{t('walkIn')}</p>
        <p className="text-xs text-text-muted mt-0.5">{t('walkInPickerHint')}</p>
      </button>
      <PatientSearchCombobox
        search={search}
        onSearchChange={setSearch}
        patients={patients}
        loading={loading || creating}
        onSelectPatient={(patient) => {
          if (creating) return;
          void onSelectPatient(patient);
        }}
        placeholder={tPatients('searchPlaceholder')}
        emptyResultsMessage={tPatients('noResults')}
      />
      <div className="flex justify-end">
        <Button type="button" variant="ghost" size="sm" disabled={creating} onClick={onCancel}>
          {tCommon('cancel')}
        </Button>
      </div>
    </div>
  );
}
