// ============================================================
// SICK VISIT — /api/sick-visit/note
// ============================================================

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { api, ApiError } from '@/lib/api';
import type { VisitNoteOk } from '@/shared/types';
import { SickVisitRequestSchema, type SickVisitRequest } from '@/shared/schemas';

export default function SickVisit() {
  const [patientAge, setPatientAge] = useState('');
  const [patientGender, setPatientGender] = useState('');
  const [chiefComplaint, setChiefComplaint] = useState('');
  const [transcript, setTranscript] = useState('');
  const [result, setResult] = useState<string | null>(null);
  const [validationError, setValidationError] = useState<string | null>(null);

  const generate = useMutation<VisitNoteOk, Error, SickVisitRequest>({
    mutationFn: (body) => api.post<VisitNoteOk>('/api/sick-visit/note', body),
    onSuccess: (data) => setResult(data.note),
  });

  function submit(e: React.FormEvent) {
    e.preventDefault();
    setValidationError(null);
    const body: SickVisitRequest = { patientAge, patientGender, chiefComplaint, transcript };
    const parsed = SickVisitRequestSchema.safeParse(body);
    if (!parsed.success) {
      setValidationError(parsed.error.issues.map((i: { message: string }) => i.message).join(', '));
      return;
    }
    setResult(null);
    generate.mutate(parsed.data);
  }

  const input = 'w-full rounded-md border border-input bg-background px-3 py-2 text-sm';

  return (
    <div className="max-w-4xl mx-auto p-6 space-y-4">
      <header>
        <h1 className="text-2xl font-semibold">Sick Visit</h1>
        <p className="text-sm text-muted-foreground">
          Chief complaint + transcript → structured sick-visit note.
        </p>
      </header>

      <form onSubmit={submit} className="space-y-4">
        <div className="grid grid-cols-3 gap-3">
          <label className="flex flex-col gap-1">
            <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Age</span>
            <input className={input} placeholder="e.g. 4 years" value={patientAge} onChange={(e) => setPatientAge(e.target.value)} />
          </label>
          <label className="flex flex-col gap-1">
            <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Gender</span>
            <select className={input} value={patientGender} onChange={(e) => setPatientGender(e.target.value)}>
              <option value="">Select</option>
              <option>Male</option>
              <option>Female</option>
            </select>
          </label>
          <label className="flex flex-col gap-1 col-span-3 md:col-span-1">
            <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Chief complaint</span>
            <input className={input} placeholder="e.g. Fever x 2 days" value={chiefComplaint} onChange={(e) => setChiefComplaint(e.target.value)} />
          </label>
        </div>

        <label className="flex flex-col gap-1">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Transcript / dictation</span>
          <textarea
            className={input + ' min-h-[200px] font-mono text-sm'}
            placeholder="Encounter narrative — transcribed or dictated."
            value={transcript}
            onChange={(e) => setTranscript(e.target.value)}
          />
        </label>

        {validationError && <div className="text-sm text-destructive">{validationError}</div>}
        {generate.error && <div className="text-sm text-destructive">{(generate.error as ApiError).message}</div>}

        <button
          type="submit"
          disabled={generate.isPending || !chiefComplaint.trim()}
          className="rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium disabled:opacity-50"
        >
          {generate.isPending ? 'Generating…' : 'Generate Note'}
        </button>
      </form>

      {result && (
        <section className="rounded-lg border border-border bg-card">
          <header className="px-4 py-2 border-b border-border flex items-center justify-between bg-muted/40">
            <h2 className="text-sm font-semibold">Sick Visit Note</h2>
            <button onClick={() => navigator.clipboard.writeText(result)} className="text-xs text-muted-foreground underline">Copy</button>
          </header>
          <div className="p-4 whitespace-pre-wrap text-sm">{result}</div>
        </section>
      )}
    </div>
  );
}
