// ============================================================
// HOSPITAL COURSE — /api/generate-hospital-course
// ============================================================

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

type SettingKind = 'floor' | 'picu' | 'nicu' | 'psych';
type FormatKind = 'auto' | 'prose' | 'dayByDay' | 'organSystem';

interface NoteEntry { date: string; type: string; content: string }

export default function HospitalCourse() {
  const [patientAge, setPatientAge] = useState('');
  const [patientGender, setPatientGender] = useState('');
  const [pmh, setPmh] = useState('');
  const [setting, setSetting] = useState<SettingKind>('floor');
  const [los, setLos] = useState('');
  const [format, setFormat] = useState<FormatKind>('auto');
  const [hAndPContent, setHAndPContent] = useState('');
  const [notesText, setNotesText] = useState('');
  const [additionalInstructions, setAdditionalInstructions] = useState('');
  const [result, setResult] = useState<{ hospitalCourse: string; format: string } | null>(null);

  const generate = useMutation<HospitalCourseOk, Error, any>({
    mutationFn: (body) => api.post<HospitalCourseOk>('/api/generate-hospital-course', body),
    onSuccess: (data) => setResult({ hospitalCourse: data.hospitalCourse, format: data.format || 'auto' }),
  });

  function submit(e: React.FormEvent) {
    e.preventDefault();
    setResult(null);
    // Notes textarea: one blank-line-separated note per block. First
    // line of each block is used as the date if it looks like one,
    // rest becomes content.
    const notes: NoteEntry[] = notesText
      .split(/\n\s*\n/)
      .map((block) => block.trim())
      .filter(Boolean)
      .map((block, i) => ({ date: `Day ${i + 1}`, type: 'Progress Note', content: block }));
    generate.mutate({
      notes,
      hAndP: hAndPContent ? { date: 'Admission', content: hAndPContent } : undefined,
      patientAge, patientGender, pmh, setting,
      los: los ? parseInt(los) : undefined,
      formatPreference: format,
      additionalInstructions: additionalInstructions || undefined,
    });
  }

  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">Hospital Course</h1>
        <p className="text-sm text-muted-foreground">
          Progress notes + H&amp;P → hospital course summary (prose, day-by-day, or organ-system format).
        </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} 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">Setting</span>
            <select className={input} value={setting} onChange={(e) => setSetting(e.target.value as SettingKind)}>
              <option value="floor">Floor</option>
              <option value="picu">PICU</option>
              <option value="nicu">NICU</option>
              <option value="psych">Psych</option>
            </select>
          </label>
        </div>

        <div className="grid grid-cols-3 gap-3">
          <label className="flex flex-col gap-1 col-span-2">
            <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">PMH</span>
            <input className={input} placeholder="e.g. Asthma, hypothyroidism" value={pmh} onChange={(e) => setPmh(e.target.value)} />
          </label>
          <label className="flex flex-col gap-1">
            <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">LOS (days)</span>
            <input className={input} type="number" value={los} onChange={(e) => setLos(e.target.value)} />
          </label>
        </div>

        <label className="flex flex-col gap-1">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Format</span>
          <select className={input} value={format} onChange={(e) => setFormat(e.target.value as FormatKind)}>
            <option value="auto">Auto (infer from setting + LOS)</option>
            <option value="prose">Prose summary</option>
            <option value="dayByDay">Day-by-day</option>
            <option value="organSystem">Organ-system (ICU)</option>
          </select>
        </label>

        <label className="flex flex-col gap-1">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">H&amp;P</span>
          <textarea className={input + ' min-h-[120px] font-mono text-sm'} value={hAndPContent} onChange={(e) => setHAndPContent(e.target.value)} />
        </label>

        <label className="flex flex-col gap-1">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
            Progress notes <span className="normal-case font-normal text-muted-foreground">(separate each note with a blank line)</span>
          </span>
          <textarea className={input + ' min-h-[200px] font-mono text-sm'} value={notesText} onChange={(e) => setNotesText(e.target.value)} />
        </label>

        <label className="flex flex-col gap-1">
          <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Additional instructions</span>
          <textarea className={input + ' min-h-[60px] text-sm'} value={additionalInstructions} onChange={(e) => setAdditionalInstructions(e.target.value)} />
        </label>

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

        <button
          type="submit"
          disabled={generate.isPending || !notesText.trim()}
          className="rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium disabled:opacity-50"
        >
          {generate.isPending ? 'Generating…' : 'Generate Hospital Course'}
        </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">
              Hospital Course <span className="text-xs font-normal text-muted-foreground">({result.format})</span>
            </h2>
            <button onClick={() => navigator.clipboard.writeText(result.hospitalCourse)} className="text-xs text-muted-foreground underline">Copy</button>
          </header>
          <div className="p-4 whitespace-pre-wrap text-sm">{result.hospitalCourse}</div>
        </section>
      )}
    </div>
  );
}
