"use client";

import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";

import { PolicyChecks, PolicyChecksSkeleton } from "@/components/employee-requests/PolicyChecks";
import { SelectedHotelBand } from "@/components/employee-requests/SelectedHotelBand";
import { FraSection, FraTotalRow } from "@/components/employee-requests/fra-primitives";
import { useBusinessSession } from "@/components/employee-requests/use-session";
import {
  hotelRequestApprovalSchema,
  type HotelRequestApprovalValues,
} from "@/features/employee-requests/schemas/hotel-request-approval.schema";
import {
  getMeetingTypes,
  previewPolicy,
  submitHotelRequest,
} from "@/services/employee-requests/employee-requests.client";
import { rememberSubmittedRequest } from "@/services/employee-requests/submitted-handoff";
import type { HotelGuestPayload, SubmittedRequest } from "@/services/employee-requests/employee-requests.types";
import type { BookNowBusinessInfo } from "@/services/employee-requests/hotel-book-now-handoff";
import { formatMoney } from "@/services/employee-requests/format";
import { HotelBusinessInfoSection } from "./HotelBusinessInfoSection";
import type { HotelRequestSelection } from "./types";

/**
 * LEIS-990 — step 3 of the hotel request, Request approval. A PAGE, not an
 * overlay — the user asked for the hotel flow to mirror the flight flow
 * exactly as it works today (FlightReviewMultiClient / PaneRequestApproval),
 * where the final step is the last pane of the same stepper rather than a
 * modal that pops up over the results. See HotelReviewClient for the
 * orchestrator this plugs into.
 *
 * Everything carried in from Review Hotel and Guest Details is READ-ONLY
 * here, same rule PaneRequestApproval follows: to change the room, rate or
 * guest you go Back a step, which is why both earlier panes stay mounted.
 * Only the business reason is typed on this screen.
 */

const COLLEAGUE_CODES = new Set([
  "COLLEAGUE_BOOKING_OFF",
  "COLLEAGUE_PROFILE_INCOMPLETE",
  "TRAVELLER_NOT_FOUND",
  "INVALID_TRAVELLER",
]);

function newIdempotencyKey(): string {
  return typeof crypto !== "undefined" && "randomUUID" in crypto
    ? crypto.randomUUID()
    : `req-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="min-w-0">
      <dt className="text-[12px] text-[var(--fra-muted)]">{label}</dt>
      <dd className="m-0 truncate text-[14px] text-[var(--fra-text)]">{value || "—"}</dd>
    </div>
  );
}

export interface PaneRequestApprovalHotelHandle {
  /**
   * Validates just the business-info fields (meetingType, justification) and
   * returns them, or null if invalid — same contract as flight's
   * PaneRequestApprovalHandle.getValidBusinessInfo, and for the same reason:
   * lets Book Now (HotelReviewClient) reuse whatever the employee already
   * typed here instead of asking again on /hotel-checkout.
   */
  getValidBusinessInfo: () => Promise<BookNowBusinessInfo | null>;
}

export function PaneRequestApprovalHotel({
  selection,
  guest,
  bookingFor,
  onSubmitting,
  formRef,
}: {
  selection: HotelRequestSelection;
  /** Step 2's validated values. Null until that step has been passed once. */
  guest: HotelGuestPayload | null;
  bookingFor: string | null;
  onSubmitting?: (busy: boolean) => void;
  /** See PaneRequestApprovalHotelHandle. Optional: nothing reads it unless
   *  the group's policy makes Book Now available at all. */
  formRef?: RefObject<PaneRequestApprovalHotelHandle | null>;
}) {
  const router = useRouter();
  const session = useBusinessSession();
  const [banner, setBanner] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const idempotencyKey = useRef<string>("");

  const ready = Boolean(guest);

  const meetingTypesQuery = useQuery({
    queryKey: ["business-meeting-types"],
    queryFn: async () => {
      const res = await getMeetingTypes();
      if (!res.success) throw new Error(res.message ?? "Could not load meeting types.");
      return res.data ?? [];
    },
    enabled: ready,
    staleTime: 5 * 60_000,
  });

  const previewQuery = useQuery({
    queryKey: [
      "hotel-policy-preview",
      selection.propertyCode,
      selection.checkIn,
      selection.checkOut,
      selection.nightlyRate,
      // Both halves of the judged figure: PRD §7 compares base + taxes, so two
      // rates with the same base and different tax are different verdicts.
      selection.taxesAndFeesPerNight,
      bookingFor ?? "self",
    ],
    queryFn: async () => {
      const res = await previewPolicy({
        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 } : {}),
      });
      if (!res.success) throw new Error(res.message ?? "Could not check your travel policy.");
      return res.data!;
    },
    enabled: ready,
    staleTime: 60_000,
  });

  const {
    register,
    handleSubmit,
    trigger,
    getValues,
    formState: { errors },
  } = useForm<HotelRequestApprovalValues>({
    mode: "onSubmit",
    reValidateMode: "onChange",
    resolver: zodResolver(hotelRequestApprovalSchema),
    defaultValues: { client: "", meetingType: "", justification: "" },
  });

  useEffect(() => {
    if (!formRef) return;
    formRef.current = {
      getValidBusinessInfo: async () => {
        const valid = await trigger(["meetingType", "justification"]);
        if (!valid) return null;
        const v = getValues();
        return {
          client: v.client?.trim() || null,
          meetingType: v.meetingType,
          justification: v.justification,
        };
      },
    };
  }, [formRef, trigger, getValues]);

  const handleSubmitted = useCallback(
    (request: SubmittedRequest) => {
      rememberSubmittedRequest(request);
      router.push(`/employee-requests/submitted?ref=${encodeURIComponent(request.reference)}`);
    },
    [router]
  );

  const onValid = useCallback(
    async (values: HotelRequestApprovalValues) => {
      if (!guest || submitting) return;
      if (session?.role === "ADMIN") {
        setBanner(
          "You are signed in as an admin, so you cannot request travel for approval. Sign in with an employee account to request this stay."
        );
        return;
      }
      setSubmitting(true);
      onSubmitting?.(true);
      setBanner(null);

      if (!idempotencyKey.current) idempotencyKey.current = newIdempotencyKey();

      const res = await submitHotelRequest(
        {
          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 } : {}),
          business: {
            meetingType: values.meetingType,
            justification: values.justification,
            client: values.client?.trim() || null,
          },
          hotelGuest: guest,
        },
        idempotencyKey.current
      );
      setSubmitting(false);
      onSubmitting?.(false);

      if (res.success && res.data) {
        handleSubmitted(res.data);
        return;
      }

      const code = res.code ?? "UNKNOWN";

      if (res.status === 401) {
        const next = `${window.location.pathname}${window.location.search}`;
        router.push(`/employee-login?next=${encodeURIComponent(next)}`);
        return;
      }
      if (code === "PROFILE_INCOMPLETE") {
        setBanner("Finish your traveller profile before requesting this stay.");
        return;
      }
      if (COLLEAGUE_CODES.has(code)) {
        setBanner(
          res.message ?? "That colleague can no longer be requested for on this stay. Go back to search and pick again."
        );
        return;
      }
      idempotencyKey.current = "";
      setBanner(res.message ?? "We could not send this request. Please try again.");
    },
    [selection, guest, bookingFor, submitting, session?.role, handleSubmitted, router, onSubmitting]
  );

  if (!ready || !guest) {
    return (
      <div className="bgColor-white shadow-sm p-4 rounded-3">
        <h3 className="subHeading fw-bold mb-2">Finish the earlier steps first</h3>
        <p className="text-sm mb-0">
          Go back to Guest Details and continue from there, so this summary has what it needs.
        </p>
      </div>
    );
  }

  const guestName = [guest.firstName, guest.middleName, guest.lastName].filter(Boolean).join(" ");
  const total = Math.round((selection.nightlyRate + selection.taxesAndFeesPerNight) * selection.nights * 100) / 100;

  return (
    <div data-corp-modal className="bz-ui">
      <form
        id="hotel-request-approval-form"
        onSubmit={(event) =>
          void handleSubmit(onValid, (formErrors) => {
            const first = Object.keys(formErrors)[0];
            setBanner("Some details are still missing. The highlighted fields show what.");
            const el = first ? document.getElementById(first) : null;
            el?.focus({ preventScroll: true });
            el?.scrollIntoView({ behavior: "smooth", block: "center" });
          })(event)
        }
        noValidate
        className="rounded-[14px] border border-[var(--fra-border)] bg-[var(--fra-surface)] p-[20px]"
      >
        <SelectedHotelBand selection={selection} />

        {banner ? (
          <div
            role="alert"
            className="mt-[16px] rounded-[10px] bg-[var(--fra-rejected-bg)] px-[14px] py-[10px] text-[13px] text-[var(--fra-rejected)]"
          >
            {banner}
          </div>
        ) : null}

        <FraSection
          step={1}
          title="Guest"
          note={
            bookingFor
              ? "Requested by you, for this colleague. Edit on step 2."
              : "From your profile, as you left it on step 2."
          }
        >
          <dl className="m-0 grid grid-cols-1 gap-x-4 gap-y-3.5 sm:grid-cols-2">
            <Row label="Name" value={guestName} />
            <Row
              label="Mobile"
              value={[guest.mobileCountryCode, guest.mobileNumber].filter(Boolean).join(" ")}
            />
          </dl>
        </FraSection>

        <HotelBusinessInfoSection
          step={2}
          register={register}
          errors={errors}
          meetingTypes={meetingTypesQuery.data ?? []}
          meetingTypesLoading={meetingTypesQuery.isPending}
          meetingTypesFailed={meetingTypesQuery.isError}
          onRetryMeetingTypes={() => void meetingTypesQuery.refetch()}
        />

        <FraSection step={3} title="Travel policy">
          {previewQuery.isPending ? (
            <PolicyChecksSkeleton />
          ) : previewQuery.isError ? (
            <p className="m-0 text-[13px] text-[var(--fra-muted)]">
              We could not check your travel policy just now. You can still submit — the approver
              sees the result either way.
            </p>
          ) : (
            <PolicyChecks policy={previewQuery.data!.policy} warnings={previewQuery.data!.warnings} />
          )}
        </FraSection>

        <div className="flex flex-col gap-[10px] pt-[16px]">
          <FraTotalRow label="Total (est.)" value={formatMoney(total, selection.currency)} />
          <p className="mb-0 text-[12px] text-[var(--fra-muted)]">
            Re-priced when your admin approves, so the final amount can differ.
          </p>
        </div>

        <button type="submit" className="hidden" aria-hidden="true" tabIndex={-1} disabled={submitting} />
      </form>
    </div>
  );
}
