"use client";

/**
 * Cancellation confirmation (FR-3.2, FR-3.5, FR-3.6, FR-3.7).
 *
 * Shows exactly what is being cancelled — event, date, party size — so nobody cancels the
 * wrong thing, and requires one deliberate tap. The request is a POST; there is no GET
 * that cancels anything.
 */
import { useState } from "react";

import { eventTitle, formatEventDate, formatEventTime, type Dictionary } from "@/lib/i18n";
import type { InvitationView } from "@/lib/view-models";

export function CancelConfirm({
  invitation,
  dict,
}: {
  invitation: InvitationView;
  dict: Dictionary;
}) {
  const [state, setState] = useState<"confirm" | "cancelled" | "reaccepted">(
    invitation.state === "cancelled" ? "cancelled" : "confirm",
  );
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const title = eventTitle(invitation.locale, invitation.event);

  async function post(path: string, body: unknown) {
    setBusy(true);
    setError(null);
    try {
      const response = await fetch(
        `/api/rsvp/${encodeURIComponent(invitation.token)}/${path}`,
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify(body),
        },
      );
      if (!response.ok) {
        const detail = await response.json().catch(() => null);
        setError(typeof detail?.detail === "string" ? detail.detail : dict.formError);
        return false;
      }
      return true;
    } catch {
      setError(dict.formError);
      return false;
    } finally {
      setBusy(false);
    }
  }

  if (state === "cancelled") {
    return (
      <section className="rounded-2xl border p-6 text-center" role="status" aria-live="polite">
        <h1 className="text-xl font-semibold">{dict.weWillMissYou}</h1>
        <p className="mt-3 text-sm opacity-70">{dict.changedYourMind}</p>
        <button
          disabled={busy}
          onClick={async () => {
            const ok = await post("reaccept", {
              name: invitation.prefill?.name ?? "Guest",
              phone: invitation.prefill?.phone ?? null,
              email: invitation.prefill?.email || null,
              party_size: invitation.currentRsvp?.partySize ?? 1,
            });
            if (ok) setState("reaccepted");
          }}
          className="mt-4 min-h-12 rounded-full border px-6 text-base disabled:opacity-60"
        >
          {dict.reAccept}
        </button>
        {error && (
          <p role="alert" className="mt-3 text-sm text-red-600">
            {error}
          </p>
        )}
      </section>
    );
  }

  if (state === "reaccepted") {
    return (
      <section className="rounded-2xl border p-6 text-center" role="status" aria-live="polite">
        <h1 className="text-xl font-semibold">{dict.alreadyAccepted}</h1>
        <a href={`/i/${invitation.token}`} className="mt-4 inline-block text-base underline">
          {title}
        </a>
      </section>
    );
  }

  // Cancellation is blocked once the event has started (FR-3.7).
  if (!invitation.canCancel) {
    return (
      <section className="rounded-2xl border p-6 text-center">
        <h1 className="text-lg font-semibold">{dict.rsvpClosed}</h1>
        {invitation.couple.hostContactPhone && (
          <p className="mt-2 text-sm">
            {dict.rsvpClosedHelp}{" "}
            <a className="underline" href={`tel:${invitation.couple.hostContactPhone}`}>
              {invitation.couple.hostContactPhone}
            </a>
          </p>
        )}
      </section>
    );
  }

  return (
    <section className="rounded-2xl border p-6 text-center">
      <h1 className="text-xl font-semibold">{dict.cancelConfirmTitle}</h1>

      <div className="mt-4 rounded-xl bg-black/5 p-4 text-left text-sm">
        <p className="opacity-70">{dict.cancelConfirmBody}</p>
        <p className="mt-1 text-base font-medium">{title}</p>
        <p>{formatEventDate(invitation.event.startsAt, invitation.locale)}</p>
        <p>{formatEventTime(invitation.event.startsAt, invitation.locale)}</p>
        {invitation.currentRsvp && (
          <p className="mt-2">
            {dict.guestsConfirmed}: <strong>{invitation.currentRsvp.partySize}</strong>
          </p>
        )}
      </div>

      {error && (
        <p role="alert" className="mt-3 text-sm text-red-600">
          {error}
        </p>
      )}

      <div className="mt-5 flex flex-col gap-2">
        <button
          disabled={busy}
          onClick={async () => {
            const ok = await post("cancel", { confirm: true, reason: null });
            if (ok) setState("cancelled");
          }}
          className="min-h-12 rounded-full bg-red-600 px-6 text-base font-medium text-white disabled:opacity-60"
        >
          {busy ? dict.submitting : dict.yesCancel}
        </button>
        <a
          href={`/i/${invitation.token}`}
          className="min-h-12 rounded-full border px-6 py-3 text-base"
        >
          {dict.keepRsvp}
        </a>
      </div>
    </section>
  );
}
