"use client";

import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";

import { toast } from "@/lib/toast";
import { cancelInstant } from "@/services/employee-requests/employee-requests.client";
import type { CancelOptions, MyRequestRow } from "@/services/employee-requests/employee-requests.types";
import { formatMoney } from "@/services/employee-requests/format";
import { fraButton } from "./fra-primitives";

/**
 * LEIS-1051 — the confirm step for an instant cancellation.
 *
 * Shows what is about to happen in the ticket's own terms: the booking, "You'll get a full
 * refund of $X to Visa •••• 1111", and when free cancellation stops, then
 * Confirm cancellation / Keep booking.
 *
 * A native <dialog> opened with showModal(), not a hand-rolled overlay: the browser puts it in
 * the top layer (no z-index fight with the page, the header or Bootstrap on routes that load
 * it), traps focus, and closes on Escape. Escape and the backdrop are ignored while the
 * request is in flight, so a user can never walk away from a cancellation half-sent.
 *
 * The page's idea of "the window is open" is only a hint. The server decides when this is
 * confirmed, and this dialog says so when the answer has changed (window closed, supplier or
 * refund trouble) instead of pretending nothing happened.
 */

export function windowLine(options: CancelOptions): string {
  if (!options.window.endsAt) return "Free cancellation until your trip starts";
  const when = new Date(options.window.endsAt).toLocaleString("en-GB", {
    day: "numeric",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  });
  // en-GB gives "20 Oct, 14:30", the format the ticket asks for.
  return `Free cancellation until ${when}`;
}

function cardLabel(card: { brand: string; last4: string } | null): string {
  if (!card) return "the card it was paid with";
  const brand = card.brand ? card.brand.charAt(0).toUpperCase() + card.brand.slice(1) : "Card";
  return `${brand} •••• ${card.last4}`;
}

function bookingSummary(row: MyRequestRow): string {
  if (row.trip.flight) return `${row.trip.flight.origin} → ${row.trip.flight.destination}`;
  if (row.trip.hotel) return row.trip.hotel.property;
  return row.reference;
}

interface InstantCancelDialogProps {
  row: MyRequestRow;
  options: CancelOptions;
  open: boolean;
  onClose: () => void;
}

export function InstantCancelDialog({ row, options, open, onClose }: InstantCancelDialogProps) {
  const ref = useRef<HTMLDialogElement>(null);
  const queryClient = useQueryClient();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<{ code?: string; message: string; canSendToSupport: boolean } | null>(null);

  useEffect(() => {
    const dialog = ref.current;
    if (!dialog) return;
    if (open && !dialog.open) {
      setError(null);
      dialog.showModal();
    } else if (!open && dialog.open) {
      dialog.close();
    }
  }, [open]);

  const refund = formatMoney(options.selfService.refundAmount, options.selfService.currency);

  const confirm = async () => {
    setBusy(true);
    setError(null);
    const res = await cancelInstant(row.id);
    setBusy(false);

    if (!res.success) {
      // A closed window changes which buttons are right, so refresh them behind the dialog.
      void queryClient.invalidateQueries({ queryKey: ["employee-requests"] });
      setError({
        code: res.code,
        message: res.message ?? "We couldn't cancel this booking. Please try again.",
        canSendToSupport: res.code === "SUPPLIER_CANCEL_FAILED" || res.code === "REFUND_FAILED",
      });
      return;
    }

    toast.success(
      res.status === 202
        ? "Booking cancelled. Your refund is being processed."
        : `Booking cancelled. A full refund of ${refund} is on its way to ${cardLabel(options.selfService.card)}.`,
    );
    await queryClient.invalidateQueries({ queryKey: ["employee-requests"] });
    onClose();
  };

  return (
    <dialog
      ref={ref}
      aria-labelledby={`cancel-title-${row.id}`}
      onCancel={(e) => {
        // Escape during the request must not close the dialog.
        if (busy) e.preventDefault();
        else onClose();
      }}
      onClick={(e) => {
        // A click on the backdrop (the dialog element itself) closes it, unless a request is running.
        if (e.target === ref.current && !busy) onClose();
      }}
      className="m-auto w-[min(92vw,460px)] rounded-[16px] border-0 p-0 shadow-[0_20px_60px_rgba(15,39,51,0.3)] backdrop:bg-[rgba(15,39,51,0.45)]"
    >
      <div className="p-[24px]" style={{ color: "var(--fra-text)" }}>
        <h2 id={`cancel-title-${row.id}`} className="m-0 text-[18px] font-extrabold" style={{ color: "var(--fra-heading)" }}>
          Cancel this booking?
        </h2>

        <div
          className="mt-[14px] rounded-[10px] px-[14px] py-[12px] text-[14px]"
          style={{ backgroundColor: "var(--fra-surface-2)", border: "1px solid var(--fra-border)" }}
        >
          <div className="font-semibold" style={{ color: "var(--fra-heading)" }}>
            {bookingSummary(row)}
          </div>
          <div className="text-[13px]" style={{ color: "var(--fra-muted)" }}>
            {row.reference}
          </div>
        </div>

        <p className="m-0 mt-[16px] text-[15px]">
          You&apos;ll get a full refund of <strong>{refund}</strong> to <strong>{cardLabel(options.selfService.card)}</strong>.
        </p>
        <p className="m-0 mt-[6px] text-[13px]" style={{ color: "var(--fra-muted)" }}>
          {windowLine(options)}. This can&apos;t be undone.
        </p>

        {error && (
          <div
            role="alert"
            className="mt-[14px] rounded-[10px] px-[12px] py-[10px] text-[13px]"
            style={{ backgroundColor: "var(--fra-rejected-bg)", color: "var(--fra-rejected)" }}
          >
            {error.message}
            {error.canSendToSupport && <> You can ask support to cancel it instead.</>}
          </div>
        )}

        <div className="mt-[20px] flex flex-wrap justify-end gap-[8px]">
          <button type="button" onClick={onClose} disabled={busy} className={fraButton.ghost}>
            {error ? "Close" : "Keep booking"}
          </button>
          {!error?.code || error.code === "CANCEL_IN_PROGRESS" || error.canSendToSupport ? (
            <button
              type="button"
              onClick={() => void confirm()}
              disabled={busy}
              className="inline-flex h-11 items-center gap-2 rounded-[var(--fra-radius-sm)] bg-[var(--fra-rejected-solid)] px-[18px] text-sm font-semibold text-white transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"
            >
              {busy ? "Cancelling…" : error ? "Try again" : "Confirm cancellation"}
            </button>
          ) : null}
        </div>
      </div>
    </dialog>
  );
}
