'use client';

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

interface PatientSearchComboboxProps {
  search: string;
  onSearchChange: (value: string) => void;
  patients: Patient[];
  loading?: boolean;
  selectedPatient?: Patient | null;
  onSelectPatient: (patient: Patient) => void;
  /** When false, sidebar uses an external summary card instead. */
  showInlineSummary?: boolean;
  canAddPatient?: boolean;
  onAddPatient?: () => void;
  placeholder?: string;
  idleHint?: string;
  emptyResultsMessage?: string;
  noPermissionMessage?: string;
  readOnly?: boolean;
  readOnlyHint?: string;
}

export function PatientSearchCombobox({
  search,
  onSearchChange,
  patients,
  loading = false,
  selectedPatient,
  onSelectPatient,
  showInlineSummary = false,
  canAddPatient = false,
  onAddPatient,
  placeholder,
  idleHint,
  emptyResultsMessage,
  noPermissionMessage,
  readOnly = false,
  readOnlyHint,
}: PatientSearchComboboxProps) {
  const tPatients = useTranslations('patients');
  const trimmed = search.trim();
  const showResults = !readOnly && trimmed.length > 0;

  function handleSelect(patient: Patient) {
    onSelectPatient(patient);
    onSearchChange('');
  }

  if (readOnly) {
    return (
      <div className="space-y-2">
        <p className="text-sm text-text-primary rounded-[var(--radius-md)] border border-border bg-background-secondary/60 px-3 py-2">
          {selectedPatient
            ? `${selectedPatient.firstName} ${selectedPatient.lastName}`
            : tPatients('emptyValue')}
        </p>
        {readOnlyHint ? <p className="text-xs text-text-muted">{readOnlyHint}</p> : null}
      </div>
    );
  }

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

      {!trimmed && !selectedPatient && idleHint ? (
        <p className="text-sm text-text-muted">{idleHint}</p>
      ) : null}

      {showResults ? (
        <div className="space-y-2 rounded-[var(--radius-md)] border border-border/60 bg-background-secondary/30 p-2">
          {loading ? (
            <p className="text-sm text-text-muted px-1 py-2">{tPatients('loadingPatients')}</p>
          ) : patients.length === 0 ? (
            <div className="space-y-2 px-1 py-1">
              <p className="text-sm text-text-muted">
                {emptyResultsMessage ?? tPatients('noResults')}
              </p>
              {canAddPatient && onAddPatient ? (
                <Button type="button" variant="primary" onClick={onAddPatient} fullWidth>
                  {tPatients('newPatient')}
                </Button>
              ) : noPermissionMessage ? (
                <p className="text-xs text-text-muted">{noPermissionMessage}</p>
              ) : null}
            </div>
          ) : (
            <div className="max-h-48 space-y-1.5 overflow-y-auto">
              {patients.map((patient) => (
                <button
                  key={patient.id}
                  type="button"
                  onClick={() => handleSelect(patient)}
                  className="w-full rounded-[var(--radius-sm)] border border-transparent px-2.5 py-2 text-left transition-colors 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 ||
                      tPatients('noContact')}
                  </p>
                </button>
              ))}
            </div>
          )}
        </div>
      ) : null}

      {showInlineSummary && selectedPatient ? (
        <div className="rounded-[var(--radius-md)] border border-border bg-background-secondary/60 px-3 py-2.5 space-y-1">
          <p className="text-sm font-medium text-text-primary">
            {selectedPatient.firstName} {selectedPatient.lastName}
          </p>
          <p className="text-xs text-text-muted">
            {formatMobileForDisplay(selectedPatient.mobile) ||
              selectedPatient.email ||
              tPatients('noContact')}
          </p>
        </div>
      ) : null}
    </div>
  );
}
