// ============================================================
// SOAP — transcript → SOAP note via /api/generate-soap
// ============================================================

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { api, ApiError } from '@/lib/api';
import type { SoapOk } from '@/shared/types';
import { SoapRequestSchema, type SoapRequest } from '@/shared/schemas';
import Recorder from '@/components/Recorder';
import EncounterToolbar from '@/components/EncounterToolbar';
import EditableResult from '@/components/EditableResult';

type SoapType = 'full' | 'subjective';
const TYPE = 'soap' as const;

export default function Soap() {
  const [label, setLabel] = useState('');
  const [patientAge, setPatientAge] = useState('');
  const [patientGender, setPatientGender] = useState('');
  const [type, setType] = useState<SoapType>('full');
  const [transcript, setTranscript] = useState('');
  const [interim, setInterim] = useState('');
  const [additionalInstructions, setAdditionalInstructions] = 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<SoapOk, Error, SoapRequest>({
    mutationFn: (body) => api.post<SoapOk>('/api/generate-soap', body),
    onSuccess: (data) => setResult(data.soap),
  });

  function submit(e: React.FormEvent) {
    e.preventDefault();
    setValidationError(null);
    const body: SoapRequest = { transcript: (interim || transcript).trim(), patientAge, patientGender, type, additionalInstructions };
    const parsed = SoapRequestSchema.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">SOAP Note</h1>
        <p className="text-sm text-muted-foreground">
          Encounter transcript → full SOAP or subjective-only narrative.
        </p>
      </header>

      <EncounterToolbar
        type={TYPE}
        label={label} setLabel={setLabel}
        transcript={transcript} generatedNote={result || ''}
        partialData={{ age: patientAge, gender: patientGender, type, additionalInstructions }}
        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?.type) setType(pd.type);
            if (pd?.additionalInstructions) setAdditionalInstructions(pd.additionalInstructions);
          } catch { /* ignore */ }
          setLabel(enc.label || '');
        }}
        onClear={() => {
          setTranscript(''); setInterim(''); setResult(null); setValidationError(null);
          setPatientAge(''); setPatientGender(''); setType('full'); setAdditionalInstructions('');
        }}
      />

      <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. 3 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">
            <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Output type</span>
            <select className={input} value={type} onChange={(e) => setType(e.target.value as SoapType)}>
              <option value="full">Full SOAP</option>
              <option value="subjective">Subjective only</option>
            </select>
          </label>
        </div>

        <Recorder
          module="soap"
          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</span>
          <textarea
            className={input + ' min-h-[200px] font-mono text-sm'}
            placeholder="Click Start recording, or type / paste the encounter transcript."
            value={displayedTranscript}
            onChange={(e) => { setTranscript(e.target.value); setInterim(''); }}
          />
        </label>

        <label className="flex flex-col gap-1">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Additional instructions <span className="text-muted-foreground normal-case font-normal">(optional)</span>
          </span>
          <textarea
            className={input + ' min-h-[60px] text-sm'}
            placeholder="e.g., 'Include return precautions', 'Add differential for otitis media'"
            value={additionalInstructions}
            onChange={(e) => setAdditionalInstructions(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 || !displayedTranscript.trim()}
          className="rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium disabled:opacity-50"
        >
          {generate.isPending ? 'Generating…' : 'Generate SOAP'}
        </button>
      </form>

      {result !== null && (
        <EditableResult
          text={result}
          onChange={setResult}
          section="soap"
          title="Generated SOAP"
          exportLabel="soap-note"
          exportType="soap"
          sourceContext={displayedTranscript}
        />
      )}
    </div>
  );
}
