"use client";

import { useRef, useState } from "react";
import { useRouter } from "next/navigation";

import { useBusinessSession } from "@/components/employee-requests/use-session";
import HotelStepNav from "./HotelStepNav";
import HotelPriceSummary from "./HotelPriceSummary";
import { PaneReviewHotel } from "./PaneReviewHotel";
import type { GuestDetailsCardHotelHandle } from "./GuestDetailsCardHotel";
import { PaneRequestApprovalHotel, type PaneRequestApprovalHotelHandle } from "./PaneRequestApprovalHotel";
import { encodeHotelSelection } from "./selection-codec";
import type { HotelRequestSelection } from "./types";
import type { HotelGuestPayload } from "@/services/employee-requests/employee-requests.types";
import { writeHotelBookNowHandoff } from "@/services/employee-requests/hotel-book-now-handoff";
import { gateFor, useHotelPolicyLimits } from "@/services/employee-requests/hotel-policy";

/** This route owns steps 2–3 of the 3-step nav; step 1 is /hotel-details. */
const STEP_OFFSET = 1;
const LAST_LOCAL_STEP = 1;

const STEP_META = [
  { nextLabel: "Review request" },
  { nextLabel: "Submit for approval" },
] as const;

/**
 * LEIS-988/989/990 — the hotel request orchestrator for /hotel-request,
 * covering steps 2 ("Review Booking") and 3 ("Request approval") of the
 * 3-step flow the user described: /hotel-details is step 1 (picking the
 * rate), this page is steps 2–3.
 *
 * Mirrors FlightReviewMultiClient's own shape: a sticky price rail with
 * Back/Next drives every step, both panes stay mounted (toggled with
 * `d-none`) so stepping back loses nothing, and the last step's Next is
 * "Submit for approval," handed off to the pane's own form rather than
 * submitted from here — one submit path, not two.
 */
export function HotelReviewClient({
  selection,
  bookingFor,
}: {
  selection: HotelRequestSelection;
  bookingFor: string | null;
}) {
  const router = useRouter();
  const [currentStep, setCurrentStep] = useState(0);

  /**
   * The group's approval gate for THIS stay's tab (LEIS-1000).
   *
   * Defaults to "approval required" while the limits are still loading, so the
   * last step can only ever change in the safe direction — the same reasoning
   * `stepIdsFor(addOnsAllowed)` uses on the flight side. A traveller must never
   * be shown "Pay now" and then have it become "Submit for approval".
   */
  const session = useBusinessSession();
  const isAdmin = session?.role === "ADMIN";
  const policyLimits = useHotelPolicyLimits({
    travelerId: bookingFor,
    countryCode: selection.countryCode || null,
  });
  const gate = gateFor(policyLimits);
  // Always false for an admin (LEIS-1004) — see FlightReviewMultiClient's
  // identical override for why: the gate reads the TRAVELLER's group, which
  // has nothing to say about an admin booking company-wide, and the backend
  // already bypasses this same gate unconditionally for them.
  const approvalRequired = isAdmin ? false : gate ? gate.approvalRequired : true;
  const [guest, setGuest] = useState<HotelGuestPayload | null>(null);
  const [submittingRequest, setSubmittingRequest] = useState(false);
  const [bookNowPending, setBookNowPending] = useState(false);
  const guestFormRef = useRef<GuestDetailsCardHotelHandle | null>(null);
  const approvalFormRef = useRef<PaneRequestApprovalHotelHandle | null>(null);

  const meta = STEP_META[currentStep];

  /** The same `hotelId:offerId:bookingFor` triple app/hotel-request/page.tsx
   *  uses as this journey's React key — stable for the life of one visit to
   *  this selection, which is exactly as long as a Book Now handoff needs to
   *  survive. */
  const hotelKey = `${selection.hotelId}:${String(selection.offerSnapshot.offerId ?? "")}`;

  function advance() {
    setCurrentStep((step) => Math.min(step + 1, LAST_LOCAL_STEP));
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  async function goNext() {
    // Review Booking — Guest Details lives on this same pane now, so the
    // gate is identical to what it was as its own step: validate, store,
    // only then advance.
    if (currentStep === 0) {
      const validGuest = await guestFormRef.current?.getValidGuest();
      if (!validGuest) return;
      setGuest(validGuest);
      advance();
      return;
    }

    // Request approval — hand off to the pane's own form.
    if (currentStep >= LAST_LOCAL_STEP) {
      const form = document.getElementById("hotel-request-approval-form") as HTMLFormElement | null;
      form?.requestSubmit();
      return;
    }

    advance();
  }

  function goPrev() {
    if (currentStep === 0) {
      // Back to hotel-details — step 1 of the 3-step flow, which is where
      // this route is always entered from.
      router.back();
      return;
    }
    setCurrentStep((step) => Math.max(step - 1, 0));
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  async function handleBookNow() {
    if (!guest || bookNowPending) return;
    setBookNowPending(true);
    // The SAME business-info fields PaneRequestApprovalHotel owns, validated
    // on THIS form rather than asked for a second time on /hotel-checkout —
    // see hotel-book-now-handoff.ts's own doc comment on why.
    const business = await approvalFormRef.current?.getValidBusinessInfo();
    setBookNowPending(false);
    if (!business) return;
    writeHotelBookNowHandoff(hotelKey, bookingFor, { hotelGuest: guest, business });
    const params = new URLSearchParams({ selection: encodeHotelSelection(selection) });
    if (bookingFor) params.set("bookingFor", bookingFor);
    router.push(`/hotel-checkout?${params.toString()}`);
  }

  return (
    <section className="py-md-5 py-3 booking-detail-listing-section">
      <div className="container webNewContent travelContent">
        <div className="row">
          <div className="col-12 mb-3">
            <HotelStepNav
              currentStep={currentStep + STEP_OFFSET}
              locked={submittingRequest}
              onStepSelect={(step) => {
                // Step 1 (Hotel Details) has no local state to select into —
                // only the two steps this route owns are selectable.
                if (step < STEP_OFFSET) return;
                setCurrentStep(step - STEP_OFFSET);
                window.scrollTo({ top: 0, behavior: "smooth" });
              }}
            />
          </div>
        </div>

        <div className="row my-3">
          <div className="col-xxl-8 col-xl-8 col-lg-8 col-md-8 col-12">
            <div className={currentStep === 0 ? undefined : "d-none"}>
              <PaneReviewHotel selection={selection} travelerId={bookingFor} guestFormRef={guestFormRef} />
            </div>
            <div className={currentStep === 1 ? undefined : "d-none"}>
              {/* LEIS-991: Request approval is always the pane here, same as
                  the flight side (LEIS-1010) — a group with no approval
                  requirement ALSO gets a Book Now action, shown in the price
                  rail directly below Submit for approval rather than under
                  this form. */}
              <PaneRequestApprovalHotel
                selection={selection}
                guest={guest}
                bookingFor={bookingFor}
                onSubmitting={setSubmittingRequest}
                formRef={approvalFormRef}
              />
            </div>
          </div>

          <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-12 mt-3 mt-md-0 d-flex flex-column gap-3">
            <HotelPriceSummary
              selection={selection}
              stepTitle={currentStep === LAST_LOCAL_STEP ? "Request Summary" : "Price Breakup"}
              nextLabel={meta.nextLabel}
              prevDisabled={submittingRequest}
              nextDisabled={submittingRequest}
              priceNote={submittingRequest ? "Sending your request…" : undefined}
              onPrev={goPrev}
              onNext={() => void goNext()}
              showBookNow={currentStep === LAST_LOCAL_STEP && !approvalRequired}
              bookNowPending={bookNowPending}
              onBookNow={() => void handleBookNow()}
              hideNext={currentStep === LAST_LOCAL_STEP && isAdmin}
              bookNowNote={
                isAdmin
                  ? "You're booking directly as an admin — this charges the company card right away, no approval needed."
                  : undefined
              }
              repriceNote={isAdmin ? "Re-priced right before payment, so the final amount can differ." : undefined}
            />
          </div>
        </div>
      </div>
    </section>
  );
}
