"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useForm, useWatch } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";

import {
  addEmployeeCard,
  listEmployeeCards,
  payDirect,
  type DirectBookingResult,
  type EmployeeCard,
} from "@/services/employee-requests/employee-checkout.client";
import {
  clearHotelBookNowHandoff,
  readHotelBookNowHandoff,
  type HotelBookNowHandoff,
} from "@/services/employee-requests/hotel-book-now-handoff";
import { decodeHotelSelection } from "./selection-codec";
import type { HotelRequestSelection } from "./types";
import { BOOKING_FOR_PARAM } from "@/services/employee-requests/booking-for";
import { getBusinessAccessToken } from "@/lib/business-session";
import { toast } from "@/lib/toast";
import { formatMoney } from "@/services/employee-requests/format";
import { BRAND_LABEL, digitsOnly, type CardBrand } from "@/services/payment-cards/card-utils";
import AddCardForm from "@/components/payment-cards/AddCardForm";

type Step = "payment" | "done";

interface CheckoutValues {
  cardId: string;
  cardCode: string;
}

function newIdempotencyKey(): string {
  return `corp-hoteldirect-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}

/**
 * Book Now for hotels (LEIS-991) — hotel sibling of FlightCheckoutClient, in
 * the SAME `.co-*`/`.bz-*` visual system, same two-step Payment/Done
 * indicator, same deliberate absence of a business-info or travel-policy
 * section (both already collected and shown on PaneRequestApprovalHotel,
 * which stays mounted regardless of whether the group needs approval — see
 * that file's getValidBusinessInfo() and hotel-book-now-handoff.ts's own
 * doc comment on why this is not asked for a second time here).
 *
 * The offer itself arrives via `?selection=`, decoded the SAME way
 * /hotel-request decodes it (selection-codec.ts) — hotel review already has
 * a working, previously-debugged mechanism for carrying the picked room+rate
 * across a navigation, and this page reuses it rather than inventing a
 * second one. Only the guest and the validated business info ride in
 * sessionStorage (hotel-book-now-handoff.ts), for the same "no request id
 * yet" reason FlightCheckoutClient's own doc comment gives: payDirectHotel()
 * creates the request only AFTER the charge succeeds.
 *
 * No re-price-on-open here, matching FlightCheckoutClient exactly: neither
 * checkout page re-prices before showing itself, despite each one's own
 * ticket nominally asking for it — see this file's PR notes.
 */
export default function HotelCheckoutClient() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const encodedSelection = searchParams.get("selection");
  const bookingFor = searchParams.get(BOOKING_FOR_PARAM);

  const [selection] = useState<HotelRequestSelection | null>(() =>
    encodedSelection ? decodeHotelSelection(encodedSelection) : null
  );
  const hotelKey = selection
    ? `${selection.hotelId}:${String(selection.offerSnapshot.offerId ?? "")}`
    : null;

  // Lazy initializer, not an effect — same reasoning as FlightCheckoutClient's
  // identical `handoff` state: it must read sessionStorage exactly once,
  // before the first paint, and must not disappear once a successful booking
  // clears it while the Done screen is still showing.
  const [handoff] = useState<HotelBookNowHandoff | null>(() =>
    hotelKey ? readHotelBookNowHandoff(hotelKey, bookingFor) : null
  );

  const [idempotencyKey] = useState(newIdempotencyKey);
  const [submitting, setSubmitting] = useState(false);
  const [payError, setPayError] = useState<string | null>(null);
  const [result, setResult] = useState<DirectBookingResult | null>(null);
  const step: Step = result ? "done" : "payment";

  const cardsQuery = useQuery({
    queryKey: ["employee-cards"],
    queryFn: async () => {
      const res = await listEmployeeCards();
      if (!res.success || !res.data) throw new Error(res.message ?? "Could not load your company cards.");
      return res.data;
    },
    staleTime: 60_000,
    enabled: Boolean(selection),
  });

  const cards = cardsQuery.data?.cards ?? [];
  const payable = cards.filter((c) => !c.expired);

  const {
    register,
    handleSubmit,
    control,
    setValue,
    formState: { errors },
  } = useForm<CheckoutValues>({
    mode: "onSubmit",
    defaultValues: { cardId: "", cardCode: "" },
  });

  const pickedCardId = useWatch({ control, name: "cardId" });
  const cardCode = useWatch({ control, name: "cardCode" });
  const chosenCardId =
    pickedCardId === "new"
      ? "new"
      : pickedCardId || payable.find((c) => c.isDefault)?.id || payable[0]?.id || "";
  const selectedCard = cards.find((c) => c.id === chosenCardId) ?? null;

  const taxesAndFees = useMemo(
    () => (selection ? selection.taxesAndFeesPerNight * selection.nights : 0),
    [selection]
  );
  const total = useMemo(
    () => (selection ? (selection.nightlyRate + selection.taxesAndFeesPerNight) * selection.nights : 0),
    [selection]
  );
  const currency = selection?.currency ?? "USD";

  const onSubmit = handleSubmit(async (values) => {
    if (submitting || !selection || !handoff || !hotelKey) return;
    setPayError(null);
    if (!chosenCardId) {
      setPayError("Select a card to pay with.");
      return;
    }
    if (chosenCardId === "new") {
      setPayError("Save the new card above first, then select it to pay.");
      return;
    }
    const digits = digitsOnly(values.cardCode);
    if (digits.length < 3 || digits.length > 4) {
      setPayError("Enter the security code.");
      return;
    }

    setSubmitting(true);

    const res = await payDirect(
      {
        type: "HOTEL",
        offer: {
          property: selection.property,
          propertyCode: selection.propertyCode,
          location: selection.location,
          countryCode: selection.countryCode,
          checkIn: selection.checkIn,
          checkOut: selection.checkOut,
          nights: selection.nights,
          roomType: selection.roomType,
          rateType: selection.rateType,
          cancellationTerms: selection.cancellationTerms,
          nightlyRate: selection.nightlyRate,
          taxesPerNight: selection.taxesAndFeesPerNight,
          currency: selection.currency,
          starRating: selection.starRating,
          isRefundable: selection.isRefundable,
          propertyType: selection.propertyType,
          chainCode: selection.chainCode,
          offerSnapshot: selection.offerSnapshot,
        },
        ...(bookingFor ? { travelerId: bookingFor } : {}),
        // Validated and typed on the review page's Request approval pane —
        // see this file's own doc comment on why this is not re-collected.
        business: {
          meetingType: handoff.business.meetingType,
          justification: handoff.business.justification,
          client: handoff.business.client ?? null,
        },
        ...(handoff.hotelGuest ? { hotelGuest: handoff.hotelGuest } : {}),
        cardId: chosenCardId,
        cardCode: digits,
      },
      idempotencyKey,
    );

    setSubmitting(false);

    if (res.success && res.data) {
      clearHotelBookNowHandoff(hotelKey, bookingFor);
      toast.success(`${res.data.reference} paid and booked.`);
      setResult(res.data);
      return;
    }

    if (res.status === 401) {
      const next = `${window.location.pathname}${window.location.search}`;
      router.push(`/employee-login?next=${encodeURIComponent(next)}`);
      return;
    }
    setPayError(res.message ?? "We could not take the payment. Please try again.");
  });

  return (
    <section className="bz-ui bz-page">
      <div className="mx-auto w-full max-w-[1100px] px-3 py-8">
        <div className="co-top">
          <div>
            <ol className="co-crumbs">
              <li>
                <Link href="/srp/hotels">Hotels</Link>
              </li>
              <li aria-current="page">Book now</li>
            </ol>
            <h1 className="co-title">Book this stay</h1>
          </div>
          <ol className="co-steps">
            <li className={step === "payment" ? "is-current" : "is-done"}>
              <span>{step === "done" ? <i className="bi bi-check" aria-hidden="true" /> : 1}</span>
              Payment
            </li>
            <li className={step === "done" ? "is-current" : ""}>
              <span>2</span>
              Done
            </li>
          </ol>
        </div>

        {!selection && (
          <div className="bz-card co-empty">
            <span className="bz-icon-tile tone-navy" aria-hidden="true">
              <i className="bi bi-wallet2" />
            </span>
            <h2 className="co-h2">Nothing to pay for</h2>
            <p>
              We couldn&rsquo;t find a stay to book. Go back to your search and click Book Now
              again.
            </p>
            <Link href="/srp/hotels" className="bz-btn bz-btn-primary">
              <i className="bi bi-search" aria-hidden="true" />
              <span>Back to search</span>
            </Link>
          </div>
        )}

        {selection && step === "payment" && (
          <form onSubmit={onSubmit} noValidate>
            <div className="co-layout">
              <div className="co-left">
                <BookingBox selection={selection} />

                <div className="bz-card co-box">
                  <div className="co-box-head">
                    <h2 className="co-h2">Payment method</h2>
                  </div>
                  {cardsQuery.isPending ? (
                    <p className="m-0 text-[13px] text-[var(--fra-muted)]">Loading your company cards…</p>
                  ) : cardsQuery.isError ? (
                    <p className="m-0 text-[13px] text-[var(--fra-rejected)]">
                      We could not load your company cards.{" "}
                      <button
                        type="button"
                        className="fra-link-btn"
                        onClick={() => void cardsQuery.refetch()}
                      >
                        Try again
                      </button>
                    </p>
                  ) : (
                    <div className="co-opts">
                      {payable.length === 0 && (
                        <p className="m-0 mb-3 text-[13px] text-[var(--fra-muted)]">
                          There is no usable company card on file yet. Add one below.
                        </p>
                      )}
                      {cards.map((card) => (
                        <EmployeeCardOption
                          key={card.id}
                          card={card}
                          selected={chosenCardId === card.id}
                          onSelect={() => setValue("cardId", card.id, { shouldValidate: true })}
                          cardCode={cardCode ?? ""}
                          onCardCode={(v) => setValue("cardCode", v)}
                          cardCodeError={errors.cardCode?.message}
                        />
                      ))}

                      <div className={`co-opt${chosenCardId === "new" ? " is-selected" : ""}`}>
                        <label className="co-opt-head">
                          <input
                            type="radio"
                            checked={chosenCardId === "new"}
                            {...register("cardId")}
                            value="new"
                          />
                          <span className="bc-tile is-blank" aria-hidden="true">
                            <i className="bi bi-plus-lg" />
                          </span>
                          <span className="co-opt-text">
                            <strong>Add a new card</strong>
                            <small>Visa, Mastercard, American Express, Discover</small>
                          </span>
                        </label>
                        {chosenCardId === "new" && (
                          <div className="co-opt-body co-new">
                            <AddCardForm
                              token={getBusinessAccessToken() ?? ""}
                              companyAddress={cardsQuery.data?.companyAddress ?? null}
                              submit={(payload) => addEmployeeCard(payload)}
                              onAdded={async () => {
                                await cardsQuery.refetch();
                                setValue("cardId", "");
                              }}
                            />
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <OrderSummarySidebar
                selection={selection}
                taxesAndFees={taxesAndFees}
                currency={currency}
                total={total}
                selectedCard={selectedCard}
                paying={submitting}
                payError={payError}
              />
            </div>
          </form>
        )}

        {selection && step === "done" && result && <DoneBox result={result} />}
      </div>
    </section>
  );
}

/** Mirrors FlightCheckoutClient's own BookingBox — "1 room · 1 guest" per
 *  LEIS-991's own field list, where flights show cabin and travellers. */
function BookingBox({ selection }: { selection: HotelRequestSelection }) {
  return (
    <div className="bz-card co-box">
      <div className="co-box-head">
        <span className="co-eyebrow">Booking</span>
      </div>
      <ul className="co-trips">
        <li>
          <span className="co-trip-icon" aria-hidden="true">
            <i className="bi bi-building" />
          </span>
          <div className="co-trip-text">
            <strong>{selection.property}</strong>
            <small>
              {selection.starRating ? `${selection.starRating}★ · ` : ""}
              {selection.location}
            </small>
            <small>
              {selection.checkIn} – {selection.checkOut} · {selection.nights} night
              {selection.nights === 1 ? "" : "s"} · {selection.roomType}
              {selection.rateType ? ` · ${selection.rateType}` : ""}
            </small>
            {selection.cancellationTerms && <small>{selection.cancellationTerms}</small>}
            <small>
              1 room · {selection.adults ?? 1} adult{(selection.adults ?? 1) === 1 ? "" : "s"}
            </small>
          </div>
        </li>
      </ul>
    </div>
  );
}

function EmployeeCardOption({
  card,
  selected,
  onSelect,
  cardCode,
  onCardCode,
  cardCodeError,
}: {
  card: EmployeeCard;
  selected: boolean;
  onSelect: () => void;
  cardCode: string;
  onCardCode: (v: string) => void;
  cardCodeError?: string;
}) {
  const brandLabel = BRAND_LABEL[card.brand as CardBrand] ?? card.brand;
  return (
    <div className={`co-opt${selected ? " is-selected" : ""}${card.expired ? " is-disabled" : ""}`}>
      <label className="co-opt-head">
        <input type="radio" name="checkoutCard" checked={selected} disabled={card.expired} onChange={onSelect} />
        <span className={`bc-tile is-${card.brand}`} aria-hidden="true">
          <b>{brandLabel.toUpperCase()}</b>
          <i>•• {card.last4}</i>
        </span>
        <span className="co-opt-text">
          <strong>
            {brandLabel} ending in {card.last4}
            {card.isDefault && <span className="bz-badge">Default</span>}
          </strong>
          <small className={card.expired ? "is-expired" : undefined}>
            {card.expired ? "Expired" : "Expires"} {String(card.expMonth).padStart(2, "0")}/
            {String(card.expYear).slice(-2)}
          </small>
        </span>
      </label>
      {selected && !card.expired && (
        <div className="co-opt-body">
          <div className="bc-field">
            <label className="bz-label" htmlFor={`cvc-${card.id}`}>
              Security code
            </label>
            <input
              type="password"
              className="bz-input"
              id={`cvc-${card.id}`}
              inputMode="numeric"
              autoComplete="cc-csc"
              placeholder="CVC"
              maxLength={4}
              value={cardCode}
              onChange={(e) => onCardCode(digitsOnly(e.target.value).slice(0, 4))}
              autoFocus
            />
            {cardCodeError && <span className="bz-error">{cardCodeError}</span>}
          </div>
          <p className="mt-2 mb-0 text-[12px] text-[var(--fra-muted)]">
            Your admin has the security code for this card.
          </p>
        </div>
      )}
    </div>
  );
}

/** Mirrors FlightCheckoutClient's own OrderSummarySidebar — "nightly rate ×
 *  nights, taxes and fees, Total, Paying with" (LEIS-991), where flights
 *  show a single included-taxes line. */
function OrderSummarySidebar({
  selection,
  taxesAndFees,
  currency,
  total,
  selectedCard,
  paying,
  payError,
}: {
  selection: HotelRequestSelection;
  taxesAndFees: number;
  currency: string;
  total: number;
  selectedCard: EmployeeCard | null;
  paying: boolean;
  payError: string | null;
}) {
  return (
    <aside className="bz-card co-summary">
      <div className="co-eyebrow">Order summary</div>
      <div className="co-trip-text mt-2">
        <strong>{selection.property}</strong>
        <small>{selection.checkIn}</small>
      </div>

      <ul className="co-lines">
        <li>
          <span>
            {formatMoney(selection.nightlyRate, currency)} × {selection.nights} night
            {selection.nights === 1 ? "" : "s"}
          </span>
          <strong>{formatMoney(selection.nightlyRate * selection.nights, currency)}</strong>
        </li>
        <li>
          <span>Taxes & fees</span>
          <strong>{formatMoney(taxesAndFees, currency)}</strong>
        </li>
      </ul>

      <dl className="co-totals">
        <div className="co-total">
          <dt>Total</dt>
          <dd>{formatMoney(total, currency)}</dd>
        </div>
      </dl>

      {selectedCard && (
        <div className="co-paying">
          <small>Paying with</small>
          <div>
            <span className={`bc-tile is-${selectedCard.brand}`} aria-hidden="true">
              <b>{(BRAND_LABEL[selectedCard.brand as CardBrand] ?? selectedCard.brand).toUpperCase()}</b>
              <i>•• {selectedCard.last4}</i>
            </span>
            <strong>
              {BRAND_LABEL[selectedCard.brand as CardBrand] ?? selectedCard.brand} ending in{" "}
              {selectedCard.last4}
            </strong>
          </div>
        </div>
      )}

      {payError && <p className="bz-error co-pay-err">{payError}</p>}

      <button type="submit" className="bz-btn bz-btn-primary co-pay" disabled={paying}>
        {paying ? (
          <Loader2 aria-hidden className="size-4 animate-spin motion-reduce:animate-none" />
        ) : (
          <i className="bi bi-lock-fill" aria-hidden="true" />
        )}
        <span>{paying ? "Paying…" : `Pay ${formatMoney(total, currency)}`}</span>
      </button>
      <p className="co-secure">
        <i className="bi bi-shield-check" aria-hidden="true" />
        Secure payment. Your card may be verified by your bank before the payment goes through.
      </p>
      <p className="co-terms">
        By paying you agree to the cancellation terms for this stay. Your company card is charged
        immediately and the booking is confirmed to the hotel.
      </p>
    </aside>
  );
}

function DoneBox({ result }: { result: DirectBookingResult }) {
  return (
    <div className="bz-card co-done" tabIndex={-1}>
      <div className="co-done-icon">
        <i className="bi bi-check-lg" aria-hidden="true" />
      </div>
      <h2 className="co-h2">Booking complete</h2>
      <p className="co-done-sub">
        {result.reference} is booked and confirmed. A confirmation email is on its way.
      </p>
      <dl className="co-receipt">
        {result.amountCharged && (
          <div>
            <dt>Amount paid</dt>
            <dd>
              {result.currency ?? "USD"} {result.amountCharged}
            </dd>
          </div>
        )}
        {result.card && (
          <div>
            <dt>Paid with</dt>
            <dd>
              {BRAND_LABEL[result.card.brand as CardBrand] ?? result.card.brand} ending in{" "}
              {result.card.last4}
            </dd>
          </div>
        )}
        <div>
          <dt>Reference</dt>
          <dd>{result.reference}</dd>
        </div>
      </dl>
      {/* LEIS-1046: no "View request status" here — same reasoning as the
          flight receipt in FlightCheckoutClient. */}
      <div className="co-done-actions">
        <Link href="/srp/hotels" className="bz-btn bz-btn-secondary">
          <i className="bi bi-search" aria-hidden="true" />
          <span>Book another stay</span>
        </Link>
      </div>
    </div>
  );
}
