'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import {
  CalendarPlus,
  CheckCircle2,
  AlertTriangle,
  Loader2,
} from 'lucide-react';
import { DenseCard } from '@sehat/ui';

/**
 * F7 — Follow-up booking surfaced once the consult is completed.
 *
 * Posts to `/api/appointments/:id/follow-up` (proxied to v2 backend). On 404
 * the panel hides itself entirely, matching the spec.
 */
interface FollowUpPanelProps {
  appointmentId: string;
  patientName?: string | null;
}

type SubmitState =
  | { kind: 'idle' }
  | { kind: 'submitting' }
  | { kind: 'success'; newAppointmentId: string }
  | { kind: 'hidden' } // endpoint not available — silently hide
  | { kind: 'error'; message: string };

function toDateTimeLocal(d: Date): string {
  // YYYY-MM-DDTHH:mm — the format expected by `<input type="datetime-local">`.
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

export function FollowUpPanel({ appointmentId, patientName }: FollowUpPanelProps) {
  const defaultWhen = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() + 14); // default: two weeks out
    d.setMinutes(0, 0, 0);
    return toDateTimeLocal(d);
  }, []);
  const minWhen = useMemo(() => {
    const d = new Date();
    d.setMinutes(d.getMinutes() + 30); // must be at least 30 min from now
    return toDateTimeLocal(d);
  }, []);

  const [when, setWhen] = useState<string>(defaultWhen);
  const [note, setNote] = useState('');
  const [state, setState] = useState<SubmitState>({ kind: 'idle' });

  if (state.kind === 'hidden') return null;

  async function submit() {
    setState({ kind: 'submitting' });
    try {
      const scheduledAt = new Date(when).toISOString();
      const res = await fetch(`/api/appointments/${appointmentId}/follow-up`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          scheduledAt,
          note: note.trim() || undefined,
        }),
      });
      if (res.status === 404) {
        // Endpoint not yet shipped — hide the panel per spec.
        setState({ kind: 'hidden' });
        return;
      }
      if (!res.ok) {
        const message = await res
          .json()
          .then((j) => (j && typeof j.message === 'string' ? j.message : null))
          .catch(() => null);
        setState({
          kind: 'error',
          message: message ?? `Request failed (${res.status})`,
        });
        return;
      }
      const created = (await res.json()) as { id: string };
      setState({ kind: 'success', newAppointmentId: created.id });
    } catch (e) {
      setState({
        kind: 'error',
        message: e instanceof Error ? e.message : 'Network error',
      });
    }
  }

  return (
    <DenseCard
      title={
        <span className="flex items-center gap-1.5">
          <CalendarPlus className="h-4 w-4 text-brand-500" /> Schedule follow-up
        </span>
      }
    >
      {state.kind === 'success' ? (
        <div className="flex items-start gap-2 rounded-md border border-success-500/30 bg-success-500/5 p-3 text-sm text-success-500">
          <CheckCircle2 className="mt-0.5 h-4 w-4 flex-shrink-0" />
          <div className="min-w-0 flex-1">
            <p className="font-semibold">Follow-up scheduled.</p>
            <Link
              href={`/appointments/${state.newAppointmentId}`}
              className="mt-1 inline-flex items-center gap-1 text-xs font-semibold underline hover:no-underline"
            >
              Open new appointment →
            </Link>
          </div>
        </div>
      ) : (
        <div className="space-y-2.5">
          <p className="text-xs text-ink-2">
            Book a follow-up for
            {patientName ? ` ${patientName}` : ' this patient'}. Default is 14
            days out — adjust the date and add an optional note.
          </p>
          <div>
            <label className="block text-[10px] font-semibold uppercase tracking-wide text-ink-2">
              When
            </label>
            <input
              type="datetime-local"
              value={when}
              min={minWhen}
              onChange={(e) => setWhen(e.target.value)}
              className="mt-1 h-9 w-full rounded-md border border-denseSurface-border bg-white px-2 text-sm text-ink-1 focus:border-brand-500 focus:outline-none focus:ring-2 focus:ring-brand-500/30"
            />
          </div>
          <div>
            <label className="block text-[10px] font-semibold uppercase tracking-wide text-ink-2">
              Note (optional)
            </label>
            <textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              rows={2}
              placeholder="Reason for follow-up, labs to review, etc."
              className="mt-1 w-full rounded-md border border-denseSurface-border bg-white p-2 text-sm text-ink-1 focus:border-brand-500 focus:outline-none focus:ring-2 focus:ring-brand-500/30"
            />
          </div>
          {state.kind === 'error' ? (
            <div className="flex items-start gap-2 rounded-md border border-danger-500/30 bg-danger-500/5 p-2 text-xs text-danger-500">
              <AlertTriangle className="mt-0.5 h-3.5 w-3.5 flex-shrink-0" />
              <span>{state.message}</span>
            </div>
          ) : null}
          <div className="flex justify-end">
            <button
              type="button"
              disabled={state.kind === 'submitting' || !when}
              onClick={() => void submit()}
              className="inline-flex items-center gap-1.5 rounded-md bg-brand-500 px-3 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {state.kind === 'submitting' ? (
                <Loader2 className="h-3.5 w-3.5 animate-spin" />
              ) : (
                <CalendarPlus className="h-3.5 w-3.5" />
              )}
              Schedule follow-up
            </button>
          </div>
        </div>
      )}
    </DenseCard>
  );
}
