// ============================================================
// 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';
import Recorder from '@/components/Recorder';
import EncounterToolbar from '@/components/EncounterToolbar';
import EditableResult from '@/components/EditableResult';
import RosPeTable, { rosAllWnl, rosClear } from '@/components/RosPeTable';
import DxPicker from '@/components/DxPicker';
import {
  ROS_SYSTEMS,
  PE_SYSTEMS,
  formatRosForAI,
  formatDxForAI,
  type RosData,
  type DxEntry,
} from '@shared/clinical/ros-pe-dx';

const TYPE = 'sickvisit' as const;

export default function SickVisit() {
  const [label, setLabel] = useState('');
  const [patientAge, setPatientAge] = useState('');
  const [patientGender, setPatientGender] = useState('');
  const [chiefComplaint, setChiefComplaint] = useState('');
  const [transcript, setTranscript] = useState('');
  const [interim, setInterim] = useState('');
  const [rosData, setRosData] = useState<RosData>({});
  const [peData, setPeData] = useState<RosData>({});
  const [diagnoses, setDiagnoses] = useState<DxEntry[]>([]);
  const [dxFreetext, setDxFreetext] = useState('');
  const [result, setResult] = useState<string | null>(null);
  const [validationError, setValidationError] = useState<string | null>(null);
  const [recError, setRecError] = 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 rosText = formatRosForAI(ROS_SYSTEMS, rosData, 'Review of Systems');
    const peText = formatRosForAI(PE_SYSTEMS, peData, 'Physical Examination');
    const dxText = formatDxForAI(diagnoses, dxFreetext);
    const body: SickVisitRequest = {
      patientAge, patientGender, chiefComplaint,
      transcript: (interim || transcript).trim(),
      ros: rosText || undefined,
      physicalExam: peText || undefined,
      diagnoses: dxText || undefined,
    };
    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';
  const displayedTranscript = interim || transcript;

  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>

      <EncounterToolbar
        type={TYPE}
        label={label} setLabel={setLabel}
        transcript={transcript} generatedNote={result || ''}
        partialData={{ age: patientAge, gender: patientGender, chiefComplaint, rosData, peData, diagnoses, dxFreetext }}
        onLoad={(enc) => {
          setTranscript(enc.transcript || '');
          setInterim('');
          setResult(enc.generated_note || null);
          try {
            const pd = enc.partial_data ? JSON.parse(enc.partial_data) : null;
            if (pd?.age) setPatientAge(pd.age);
            if (pd?.gender) setPatientGender(pd.gender);
            if (pd?.chiefComplaint) setChiefComplaint(pd.chiefComplaint);
            if (pd?.rosData) setRosData(pd.rosData);
            if (pd?.peData) setPeData(pd.peData);
            if (pd?.diagnoses) setDiagnoses(pd.diagnoses);
            if (pd?.dxFreetext) setDxFreetext(pd.dxFreetext);
          } catch { /* ignore */ }
          setLabel(enc.label || '');
        }}
        onClear={() => {
          setTranscript(''); setInterim(''); setResult(null); setValidationError(null);
          setPatientAge(''); setPatientGender(''); setChiefComplaint('');
          setRosData({}); setPeData({}); setDiagnoses([]); setDxFreetext('');
        }}
      />

      <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>

        <Recorder
          module="sickvisit"
          onTranscript={(text, meta) => {
            setTranscript((prev) => (meta.appended ? (prev ? prev + ' ' + text : text) : text));
            setInterim('');
            setRecError(null);
          }}
          onInterim={(t) => setInterim(t ? (transcript ? transcript + ' ' + t : t) : '')}
          onError={(msg) => setRecError(msg)}
        />
        {recError && <div className="text-sm text-destructive">{recError}</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="Click Start recording, or type / paste encounter narrative."
            value={displayedTranscript}
            onChange={(e) => { setTranscript(e.target.value); setInterim(''); }}
          />
        </label>

        <div className="rounded-lg border border-border bg-card">
          <div className="px-3 py-2 flex items-center justify-between bg-muted/40 border-b border-border">
            <span className="text-xs font-semibold uppercase tracking-wider">Review of Systems</span>
            <div className="flex gap-1">
              <button type="button" onClick={() => setRosData(rosAllWnl(ROS_SYSTEMS, rosData))} className="text-xs rounded border border-border px-2 py-1 hover:bg-muted">✓ All WNL</button>
              <button type="button" onClick={() => setRosData(rosClear(rosData, ROS_SYSTEMS))} className="text-xs rounded border border-border px-2 py-1 hover:bg-muted">Clear</button>
            </div>
          </div>
          <RosPeTable
            systems={ROS_SYSTEMS}
            data={rosData}
            onChange={setRosData}
            btnLabels={{ wnl: 'WNL', abnormal: 'Abnormal', notrev: 'Not reviewed' }}
            testIdPrefix="sv-ros"
          />
        </div>

        <div className="rounded-lg border border-border bg-card">
          <div className="px-3 py-2 flex items-center justify-between bg-muted/40 border-b border-border">
            <span className="text-xs font-semibold uppercase tracking-wider">Physical Examination</span>
            <div className="flex gap-1">
              <button type="button" onClick={() => setPeData(rosAllWnl(PE_SYSTEMS, peData))} className="text-xs rounded border border-border px-2 py-1 hover:bg-muted">✓ All Normal</button>
              <button type="button" onClick={() => setPeData(rosClear(peData, PE_SYSTEMS))} className="text-xs rounded border border-border px-2 py-1 hover:bg-muted">Clear</button>
            </div>
          </div>
          <RosPeTable
            systems={PE_SYSTEMS}
            data={peData}
            onChange={setPeData}
            btnLabels={{ wnl: 'Normal', abnormal: 'Abnormal', notrev: 'Not examined' }}
            testIdPrefix="sv-pe"
          />
        </div>

        <div className="rounded-lg border border-border bg-card p-3 space-y-2">
          <span className="text-xs font-semibold uppercase tracking-wider">Diagnoses (ICD-10)</span>
          <DxPicker value={diagnoses} onChange={setDiagnoses} testIdPrefix="sv-dx" />
          <label className="block">
            <span className="text-[11px] text-muted-foreground">Additional free-text diagnosis / note (optional)</span>
            <input
              type="text"
              value={dxFreetext}
              onChange={(e) => setDxFreetext(e.target.value)}
              className={input + ' text-sm'}
              placeholder="e.g. Follow up in 48 hours if not improving"
            />
          </label>
        </div>

        {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 !== null && (
        <EditableResult
          text={result}
          onChange={setResult}
          section="sickvisit"
          title="Sick Visit Note"
          exportLabel="sick-visit-note"
          exportType="sick-visit"
          sourceContext={displayedTranscript}
        />
      )}
    </div>
  );
}
