'use client';

/**
 * Wraps the appointment status journey + a Sign & finalize CTA the doctor
 * uses post-call. Renders three visual states:
 *
 *   • In-progress  — journey at 3rd step, no CTA (call still live).
 *   • Completed    — journey at 4th step, amber 'Finalize' card with
 *                    Sign & finalize button.
 *   • Finalized    — journey at 5th step, green locked banner with
 *                    "Only admin can edit" hint.
 */

import { useCallback, useEffect, useState } from 'react';
import { CheckCircle2, ShieldCheck, AlertCircle, Loader2 } from 'lucide-react';
import {
  AppointmentJourney,
  resolveJourneyStep,
} from '@/components/appointment-journey';

interface NoteShape {
  id?: string;
  signedAt?: string | null;
}

export function FinalizeBanner({
  appointmentId,
  status,
}: {
  appointmentId: string;
  status: string;
}) {
  const [note, setNote] = useState<NoteShape | null>(null);
  const [loading, setLoading] = useState(true);
  const [signing, setSigning] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/appointments/${appointmentId}/notes`, {
        cache: 'no-store',
      });
      if (res.ok) {
        const body = (await res.json().catch(() => null)) as NoteShape | null;
        setNote(body ?? null);
      } else if (res.status === 404) {
        setNote(null);
      }
    } finally {
      setLoading(false);
    }
  }, [appointmentId]);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  // Re-fetch when the parent flips status to completed (post end-call).
  useEffect(() => {
    if (status === 'completed') void refresh();
  }, [status, refresh]);

  async function finalize(): Promise<void> {
    setSigning(true);
    setError(null);
    try {
      const res = await fetch(`/api/appointments/${appointmentId}/finalize`, {
        method: 'POST',
      });
      if (!res.ok) {
        const body = (await res.json().catch(() => null)) as { message?: string } | null;
        throw new Error(body?.message ?? `Failed (${res.status})`);
      }
      await refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Could not finalize.');
    } finally {
      setSigning(false);
    }
  }

  const journeyStep = resolveJourneyStep({
    status,
    noteSignedAt: note?.signedAt ?? null,
  });
  const isSigned = !!note?.signedAt;
  const canFinalize = status === 'completed' && !isSigned;

  return (
    <div className="space-y-3">
      <AppointmentJourney current={journeyStep} tone="light" />

      {canFinalize ? (
        <div className="flex items-start gap-3 rounded-lg border border-amber-300 bg-amber-50 p-3">
          <AlertCircle className="mt-0.5 h-4 w-4 flex-shrink-0 text-amber-700" />
          <div className="flex-1">
            <p className="text-sm font-semibold text-amber-900">
              Consultation pending finalization
            </p>
            <p className="mt-0.5 text-xs text-amber-800">
              Notes and prescription are still editable. Sign &amp; finalize when
              you&apos;re done to lock the record — only admins can edit after that.
              The system also auto-locks after the 3-hour post-call window.
            </p>
          </div>
          <button
            type="button"
            onClick={() => void finalize()}
            disabled={signing}
            className="inline-flex flex-shrink-0 items-center gap-1.5 rounded-md bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-emerald-700 disabled:opacity-50"
          >
            {signing ? (
              <Loader2 className="h-3.5 w-3.5 animate-spin" />
            ) : (
              <CheckCircle2 className="h-3.5 w-3.5" />
            )}
            {signing ? 'Signing…' : 'Sign & finalize'}
          </button>
        </div>
      ) : null}

      {isSigned ? (
        <div className="flex items-start gap-3 rounded-lg border border-emerald-300 bg-emerald-50 p-3">
          <ShieldCheck className="mt-0.5 h-4 w-4 flex-shrink-0 text-emerald-700" />
          <div className="flex-1">
            <p className="text-sm font-semibold text-emerald-900">
              Consultation finalized
            </p>
            <p className="mt-0.5 text-xs text-emerald-800">
              Notes and prescription are locked. Contact an admin if a
              correction is needed.
            </p>
          </div>
        </div>
      ) : null}

      {error ? (
        <p className="rounded-md border border-red-300 bg-red-50 px-3 py-2 text-xs text-red-700">
          {error}
        </p>
      ) : null}

      {loading && !note ? (
        <p className="text-[11px] text-ink-3">Loading consultation status…</p>
      ) : null}
    </div>
  );
}
