// ============================================================
// CHART REVIEW — /api/generate-chart-review
// ============================================================

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

type ReviewType = 'outpatient' | 'subspecialty' | 'ed';

interface VisitInput { date: string; content: string; labs: string }

function emptyVisit(): VisitInput { return { date: '', content: '', labs: '' }; }

export default function ChartReview() {
  const [type, setType] = useState<ReviewType>('outpatient');
  const [patientAge, setPatientAge] = useState('');
  const [patientGender, setPatientGender] = useState('');
  const [pmh, setPmh] = useState('');
  const [visits, setVisits] = useState<VisitInput[]>([emptyVisit()]);
  const [additionalInstructions, setAdditionalInstructions] = useState('');
  const [result, setResult] = useState<string | null>(null);

  const generate = useMutation<ChartReviewOk, Error, any>({
    mutationFn: (body) => api.post<ChartReviewOk>('/api/generate-chart-review', body),
    onSuccess: (data) => setResult(data.review),
  });

  function updateVisit(i: number, patch: Partial<VisitInput>) {
    setVisits((vs) => vs.map((v, idx) => (idx === i ? { ...v, ...patch } : v)));
  }

  function submit(e: React.FormEvent) {
    e.preventDefault();
    setResult(null);
    const filled = visits.filter((v) => v.content.trim());
    generate.mutate({
      type,
      patientAge, patientGender, pmh,
      visits: type === 'outpatient' ? filled : undefined,
      subspecialty: type === 'subspecialty' ? filled : undefined,
      edVisits: type === 'ed' ? filled : undefined,
      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">Chart Review</h1>
        <p className="text-sm text-muted-foreground">
          Past visits → summary for pre-charting.
        </p>
      </header>

      <form onSubmit={submit} className="space-y-4">
        <div className="grid grid-cols-4 gap-3">
          <label className="flex flex-col gap-1">
            <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Review type</span>
            <select className={input} value={type} onChange={(e) => setType(e.target.value as ReviewType)}>
              <option value="outpatient">Outpatient</option>
              <option value="subspecialty">Subspecialty</option>
              <option value="ed">ED</option>
            </select>
          </label>
          <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">PMH</span>
            <input className={input} value={pmh} onChange={(e) => setPmh(e.target.value)} />
          </label>
        </div>

        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <span className="text-sm font-semibold">Visits</span>
            <button
              type="button"
              onClick={() => setVisits((v) => [...v, emptyVisit()])}
              className="text-xs rounded-md border border-border px-2 py-1"
            >
              + Add visit
            </button>
          </div>
          {visits.map((v, i) => (
            <div key={i} className="rounded-lg border border-border p-3 space-y-2 bg-card">
              <div className="flex items-center gap-2">
                <input
                  type="date"
                  className={input + ' max-w-xs'}
                  value={v.date}
                  onChange={(e) => updateVisit(i, { date: e.target.value })}
                />
                {visits.length > 1 && (
                  <button
                    type="button"
                    onClick={() => setVisits(vs => vs.filter((_, idx) => idx !== i))}
                    className="text-xs text-destructive"
                  >
                    Remove
                  </button>
                )}
              </div>
              <textarea
                className={input + ' min-h-[100px] font-mono text-sm'}
                placeholder="Visit note content — paste here."
                value={v.content}
                onChange={(e) => updateVisit(i, { content: e.target.value })}
              />
              <textarea
                className={input + ' min-h-[60px] font-mono text-xs'}
                placeholder="Labs from this visit (optional)"
                value={v.labs}
                onChange={(e) => updateVisit(i, { labs: e.target.value })}
              />
            </div>
          ))}
        </div>

        <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'}
            placeholder="e.g. 'Focus on thyroid management', 'Highlight medication changes'"
            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 || !visits.some((v) => v.content.trim())}
          className="rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium disabled:opacity-50"
        >
          {generate.isPending ? 'Generating…' : 'Generate Chart Review'}
        </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">Chart Review</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>
  );
}
