"use client";

import Link from "next/link";
import { useEffect, useState } from "react";

import { getActiveBusinessSession } from "@/lib/business-session";
import { digitsOnly } from "@/services/payment-cards/card-utils";
import { listEmployeeCards, type EmployeeCard } from "@/services/employee-requests/employee-checkout.client";
import { getSupportPayment, paySupportPayment, type SupportPaymentReceipt, type SupportPaymentView } from "@/services/employee-requests/support-payment.client";

/**
 * LEIS-1056 — pay what a change costs, from the link support emailed.
 *
 * Only the booker (or their company admin) can open it; anyone else sees "not valid", as if the link did not exist.
 * The card list is the same one checkout uses. The security code is typed here, sent once, and not kept.
 */
export default function SupportPaymentPage({ token }: { token: string }) {
  const [state, setState] = useState<"loading" | "signin" | "invalid" | "ready">("loading");
  const [view, setView] = useState<SupportPaymentView | null>(null);
  const [cards, setCards] = useState<EmployeeCard[]>([]);
  const [cardId, setCardId] = useState<string | null>(null);
  const [cardCode, setCardCode] = useState("");
  const [paying, setPaying] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [receipt, setReceipt] = useState<SupportPaymentReceipt | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      if (!getActiveBusinessSession()) {
        if (!cancelled) setState("signin");
        return;
      }
      const [pay, list] = await Promise.all([getSupportPayment(token), listEmployeeCards()]);
      if (cancelled) return;
      if (!pay.success || !pay.data) {
        setState("invalid");
        return;
      }
      setView(pay.data);
      const usable = list.data?.cards ?? [];
      setCards(usable);
      setCardId((usable.find((c) => c.isDefault && !c.expired) ?? usable.find((c) => !c.expired))?.id ?? null);
      setState("ready");
    })();
    return () => {
      cancelled = true;
    };
  }, [token]);

  const money = (v: string, cur: string) => `${cur} ${Number(v).toFixed(2)}`;

  const pay = async () => {
    if (!view) return;
    setError(null);
    if (!cardId) return setError("Select a card to pay with.");
    const code = digitsOnly(cardCode);
    if (code.length < 3 || code.length > 4) return setError("Enter the card’s security code (3 or 4 digits).");
    setPaying(true);
    const res = await paySupportPayment(token, { cardId, cardCode: code });
    setPaying(false);
    setCardCode("");
    if (res.success && res.data) {
      setReceipt(res.data);
      return;
    }
    if (res.code === "ALREADY_PAID") {
      setView({ ...view, status: "PAID" });
      return;
    }
    if (res.code === "EXPIRED") {
      setView({ ...view, status: "EXPIRED" });
      return;
    }
    setError(res.message ?? "The payment did not go through. Please try again or choose another card.");
  };

  const shell = (children: React.ReactNode) => (
    <section className="mx-auto w-full max-w-[560px] px-4 py-10">
      <div className="rounded-[14px] border border-[var(--fra-border,#e5e7eb)] bg-white p-6 shadow-sm">{children}</div>
    </section>
  );

  if (state === "loading") return shell(<p className="m-0 text-sm text-slate-500">Loading…</p>);

  if (state === "signin") {
    return shell(
      <>
        <h1 className="m-0 mb-2 text-xl font-bold">Sign in to pay</h1>
        <p className="mb-4 text-sm text-slate-600">Sign in with the account that booked this trip, then open the link in your email again.</p>
        <Link href="/employee-login" className="inline-flex h-11 items-center rounded-lg bg-black px-5 text-sm font-semibold text-white">
          Sign in
        </Link>
      </>,
    );
  }

  if (state === "invalid" || !view) {
    return shell(
      <>
        <h1 className="m-0 mb-2 text-xl font-bold">This payment link is not valid</h1>
        <p className="m-0 text-sm text-slate-600">It may have been replaced by a newer one, or it belongs to another account. Check your email for the latest link, or reply to the support email.</p>
      </>,
    );
  }

  if (receipt || view.status === "PAID") {
    return shell(
      <>
        <h1 className="m-0 mb-2 text-xl font-bold">Payment received</h1>
        <p className="mb-3 text-sm text-slate-600">
          {receipt ? `${money(receipt.amount, receipt.currency)} was charged to ${receipt.card.brand} •••• ${receipt.card.last4}.` : "This has already been paid."}{" "}
          leisure.com support will finish your change and email you the new confirmation.
        </p>
        <Link href="/employee-requests" className="text-sm font-semibold underline">
          Back to My requests
        </Link>
      </>,
    );
  }

  if (view.status === "EXPIRED") {
    return shell(
      <>
        <h1 className="m-0 mb-2 text-xl font-bold">This payment link has expired</h1>
        <p className="m-0 text-sm text-slate-600">Reply to the support email and we will send you a new one.</p>
      </>,
    );
  }

  if (view.status === "PROCESSING") {
    return shell(
      <>
        <h1 className="m-0 mb-2 text-xl font-bold">Payment in progress</h1>
        <p className="m-0 text-sm text-slate-600">A payment for this change is already being processed. Please refresh this page in a minute. Do not pay again.</p>
      </>,
    );
  }

  const payable = cards.filter((c) => !c.expired);
  return shell(
    <>
      <h1 className="m-0 mb-1 text-xl font-bold">Pay for your change</h1>
      <p className="mb-4 text-sm text-slate-600">
        {view.tripReference} · {view.tripLabel} · support reference {view.caseReference}
      </p>

      <dl className="mb-5 space-y-2 rounded-lg border border-slate-200 bg-slate-50 p-3 text-sm">
        {Number(view.fee) > 0 && (
          <div className="flex justify-between"><dt className="text-slate-500">Change fee</dt><dd>{money(view.fee, view.currency)}</dd></div>
        )}
        {Number(view.extra) > 0 && (
          <div className="flex justify-between"><dt className="text-slate-500">Fare difference</dt><dd>{money(view.extra, view.currency)}</dd></div>
        )}
        <div className="flex justify-between border-t border-slate-200 pt-2 font-semibold">
          <dt>Total to pay</dt>
          <dd>{money(view.amount, view.currency)}</dd>
        </div>
      </dl>

      <fieldset className="mb-4">
        <legend className="mb-2 text-sm font-semibold">Pay with</legend>
        {payable.length === 0 ? (
          <p className="m-0 text-sm text-red-600">There is no usable company card. Ask your admin to add one under Payment methods.</p>
        ) : (
          <div className="space-y-2">
            {cards.map((c) => (
              <label key={c.id} className={`flex items-center gap-3 rounded-lg border px-3 py-2 text-sm ${c.expired ? "opacity-50" : "cursor-pointer"} ${cardId === c.id ? "border-black" : "border-slate-200"}`}>
                <input type="radio" name="card" disabled={c.expired} checked={cardId === c.id} onChange={() => setCardId(c.id)} />
                <span className="font-medium">{c.brand} •••• {c.last4}</span>
                <span className="ml-auto text-xs text-slate-500">{c.expired ? "Expired" : `Exp ${String(c.expMonth).padStart(2, "0")}/${String(c.expYear).slice(-2)}`}</span>
              </label>
            ))}
          </div>
        )}
      </fieldset>

      <div className="mb-4">
        <label htmlFor="sp-cvc" className="mb-1 block text-sm font-semibold">Security code (CVC)</label>
        <input
          id="sp-cvc"
          inputMode="numeric"
          autoComplete="off"
          maxLength={4}
          value={cardCode}
          onChange={(e) => setCardCode(digitsOnly(e.target.value))}
          className="h-11 w-28 rounded-lg border border-slate-300 px-3 text-sm"
          aria-invalid={!!error}
        />
        <p className="mt-1 text-xs text-slate-500">Used once to take this payment. We never store it.</p>
      </div>

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

      <button
        type="button"
        onClick={pay}
        disabled={paying || payable.length === 0}
        className="inline-flex h-11 items-center rounded-lg bg-black px-6 text-sm font-semibold text-white disabled:opacity-50"
      >
        {paying ? "Processing…" : `Pay ${money(view.amount, view.currency)}`}
      </button>
      {view.expiresAt && <p className="mt-3 text-xs text-slate-500">This link is open until {new Date(view.expiresAt).toLocaleDateString("en-US", { day: "numeric", month: "short", year: "numeric" })}.</p>}
    </>,
  );
}
