"use client";

import { useCallback, useEffect, useMemo, 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 { BusinessInfoSection } from "@/components/employee-requests/BusinessInfoSection";
import type { BookNowBusinessInfo } from "@/services/employee-requests/book-now-handoff";
import { PolicyChecks, PolicyChecksSkeleton } from "@/components/employee-requests/PolicyChecks";
import { SelectedFlightBand } from "@/components/employee-requests/SelectedFlightBand";
import { FraSection, FraTotalRow } from "@/components/employee-requests/fra-primitives";
import { useBusinessSession } from "@/components/employee-requests/use-session";
import {
  requestApprovalSchema,
  type RequestApprovalValues,
} from "@/features/employee-requests/schemas/request-approval.schema";
import {
  getMeetingTypes,
  previewPolicy,
  submitFlightRequest,
} from "@/services/employee-requests/employee-requests.client";
import { rememberSubmittedRequest } from "@/services/employee-requests/submitted-handoff";
import { clearFlightRequestDraft } from "@/services/employee-requests/request-draft";
import {
  companionsFrom,
  travellerOverrideFrom,
} from "@/services/employee-requests/traveller-payload";
import type {
  FlightOfferPayload,
  FlightSubmitRequestPayload,
  SubmittedRequest,
} from "@/services/employee-requests/employee-requests.types";
import type { TravelerDetailsFormData } from "@/services/flights/traveler-details.schema";

/**
 * Step 4 of the flight request — Request approval (LEIS-966).
 *
 * A PAGE, not the E4 overlay. The overlay still exists and hotels will keep
 * using it; for flights this is the last step of the same stepper, so the
 * employee can go Back and change the flight, the travellers or the bags
 * without losing anything.
 *
 * Everything carried in from the earlier steps is READ-ONLY here, per the
 * brief: the flight and its fare option and bags (step 1 and 3), the traveller
 * details (step 2) and the additional cost. Only the business reason is typed
 * on this screen. To change anything else you go back a step — which is why
 * every pane stays mounted.
 *
 * ── The money ───────────────────────────────────────────────────────────────
 *
 * `offer.fare` is the itinerary EXCLUDING bags, and `offer.addOns.extraBagsCost`
 * carries them, so `Total (est.) = fare + bags`. The server re-derives
 * `additional_cost` from the same `addOns` block and ignores anything this form
 * might put in `business.additionalCost` — which is why that field is rendered
 * read-only rather than merely defaulted.
 */

/** New key per attempt; reused across retries of the SAME draft. */
function newIdempotencyKey(): string {
  return typeof crypto !== "undefined" && "randomUUID" in crypto
    ? crypto.randomUUID()
    : `req-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}

/** Codes that mean the chosen colleague is no longer a valid traveller. */
const COLLEAGUE_CODES = new Set([
  "COLLEAGUE_BOOKING_OFF",
  "COLLEAGUE_PASSPORT_REQUIRED",
  "COLLEAGUE_PROFILE_INCOMPLETE",
  "TRAVELLER_NOT_FOUND",
]);

function money(amount: number, symbol: string): string {
  return `${symbol}${amount.toFixed(2)}`;
}

/** One read-only row of the traveller summary. */
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 PaneRequestApprovalHandle {
  /**
   * Validates just the business-info fields (meetingType, justification —
   * the two actually required) and returns them, or null if invalid, in
   * which case the usual field errors are shown on THIS form, same as a
   * normal submit would.
   *
   * Lets Book Now (FlightReviewMultiClient) use whatever the employee has
   * already typed here instead of asking for it again on /flight-checkout —
   * see book-now-handoff.ts's own doc comment on why that mattered.
   */
  getValidBusinessInfo: () => Promise<BookNowBusinessInfo | null>;
}

export function PaneRequestApproval({
  offer,
  travelers,
  contact,
  bookingFor,
  currencySymbol,
  bagCost,
  clientRef,
  onSubmitting,
  formRef,
}: {
  /** Built from the priced offer; null while the earlier steps are incomplete. */
  offer: FlightOfferPayload | null;
  /** Step 2's validated values. Null until that step has been passed once. */
  travelers: TravelerDetailsFormData | null;
  contact: TravelerDetailsFormData["contact"] | null;
  bookingFor: string | null;
  currencySymbol: string;
  bagCost: number;
  clientRef: string;
  onSubmitting?: (busy: boolean) => void;
  /** See PaneRequestApprovalHandle. Optional: nothing reads it unless the
   *  group's policy makes Book Now available at all. */
  formRef?: RefObject<PaneRequestApprovalHandle | 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(offer && travelers);

  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,
  });

  /**
   * The traveller block the submit will send — and the preview must judge.
   *
   * Built here rather than at submit so the two cannot diverge: a verdict shown
   * against the profile's passport while the request records the one typed on
   * step 2 would be a policy answer for a different trip.
   */
  // Both derivations live in traveller-payload.ts, shared with Employee
  // Checkout (LEIS-983): the AIRIMP mononym rule and the blank-to-null
  // conversion are the kind of thing a second copy gets subtly wrong.
  const travellerOverride = useMemo(() => travellerOverrideFrom(travelers), [travelers]);
  const companions = useMemo(() => companionsFrom(travelers), [travelers]);

  const previewQuery = useQuery({
    // Keyed on what identifies the trip, not the whole object — a fresh
    // `offerSnapshot.capturedAt` on every build would refetch forever. The
    // traveller is part of that identity: the verdict is their group's.
    queryKey: [
      "policy-preview",
      offer?.origin,
      offer?.destination,
      offer?.departDate,
      offer?.fare,
      offer?.cabin,
      bookingFor ?? "self",
    ],
    queryFn: async () => {
      const res = await previewPolicy({
        type: "FLIGHT",
        offer: offer!,
        ...(bookingFor ? { travelerId: bookingFor } : {}),
        ...(travellerOverride ? { traveller: travellerOverride } : {}),
      });
      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<RequestApprovalValues>({
    // Errors show the moment a field is fixed rather than only at the next
    // submit — this form is short and all of it is on screen at once.
    mode: "onSubmit",
    reValidateMode: "onChange",
    resolver: zodResolver(
      requestApprovalSchema({
        // Both false and no travellers: every passenger detail was collected
        // and validated on step 2 by the booking form's own schema. This
        // schema runs here only for the business-reason fields, and asking it
        // to re-validate a party it is not rendering would fail on an empty
        // array it was never given.
        needsPassport: false,
        needsCompanionPassport: false,
        departDate: offer?.departDate ?? "",
        expectedTravellers: 0,
      })
    ),
    defaultValues: {
      client: "",
      opportunity: "",
      meetingType: "",
      priority: "NORMAL",
      justification: "",
      // Never typed here — the server derives it from the bags. Kept in the
      // form only because the shared schema declares it.
      additionalCost: "",
      travellers: [],
    },
  });

  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,
          opportunity: v.opportunity?.trim() || null,
          meetingType: v.meetingType,
          priority: v.priority,
          justification: v.justification,
        };
      },
    };
  }, [formRef, trigger, getValues]);

  const handleSubmitted = useCallback(
    (request: SubmittedRequest) => {
      // The submitted screen renders from this when there is no
      // GET /business/requests/:id to read back.
      rememberSubmittedRequest(request);
      // The draft described a request that now exists; leaving it would restore
      // a half-filled form over a trip already in the approver's queue.
      clearFlightRequestDraft(clientRef, bookingFor);
      router.push(`/employee-requests/submitted?ref=${encodeURIComponent(request.reference)}`);
    },
    [router, clientRef, bookingFor]
  );

  const onValid = useCallback(
    async (values: RequestApprovalValues) => {
      if (!offer || submitting) return;
      // The server refuses an admin too; saying so before a round trip is
      // kinder than after one.
      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 trip."
        );
        return;
      }
      setSubmitting(true);
      onSubmitting?.(true);
      setBanner(null);

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

      const payload: FlightSubmitRequestPayload = {
        type: "FLIGHT",
        offer,
        ...(bookingFor ? { travelerId: bookingFor } : {}),
        business: {
          meetingType: values.meetingType,
          justification: values.justification,
          client: values.client?.trim() || null,
          opportunity: values.opportunity?.trim() || null,
          // Deliberately NOT sent. LEIS-966 makes this read-only and the server
          // derives it from `offer.addOns`; sending a number here would be
          // ignored at best and misleading at worst.
          additionalCost: null,
          priority: values.priority,
        },
        ...(travellerOverride ? { traveller: travellerOverride } : {}),
        ...(companions.length > 0 ? { travellers: companions } : {}),
      };

      const res = await submitFlightRequest(payload, 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 a trip.");
        return;
      }
      if (COLLEAGUE_CODES.has(code)) {
        setBanner(
          res.message ??
            "That colleague can no longer be requested for on this trip. Go back to search and pick again."
        );
        return;
      }
      // A fresh key for a genuinely new attempt: the old one would replay the
      // failed draft rather than send the corrected one.
      idempotencyKey.current = "";
      setBanner(res.message ?? "We could not send this request. Please try again.");
    },
    [
      offer,
      submitting,
      session?.role,
      bookingFor,
      travellerOverride,
      companions,
      handleSubmitted,
      router,
      onSubmitting,
    ]
  );

  if (!ready || !offer) {
    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 Traveler Details and continue from there, so this summary has the
          details it needs.
        </p>
      </div>
    );
  }

  const lead = travelers!.travelers[0];
  const leadName = [lead?.firstName, lead?.lastName].filter(Boolean).join(" ").trim();
  const fare = offer.fare;
  const total = fare + bagCost;
  const extraBags = offer.addOns?.extraBags ?? 0;

  return (
    <div data-corp-modal className="bz-ui">
      <form
        id="request-approval-form"
        onSubmit={(event) =>
        void handleSubmit(onValid, (formErrors) => {
          // The rail's button drives this form through requestSubmit(), so a
          // failed validation would otherwise look like a dead button — the
          // error may be below the fold, and the press itself gives no
          // feedback at all. Say so, then put them on the first bad field.
          const first = Object.keys(formErrors)[0];
          setBanner(
            first === "confirmed"
              ? "Confirm that the traveller details match the passports before submitting."
              : "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]"
      >
        <SelectedFlightBand offer={offer} />

        {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}

        {/* 1 · Traveller — step 2's values, read-only. Changing them means
            going back, which is what the stepper is for. */}
        <FraSection
          step={1}
          title="Traveller"
          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={leadName} />
            <Row label="Email" value={contact?.email ?? ""} />
            <Row
              label="Mobile"
              value={[contact?.countryCode, contact?.phone].filter(Boolean).join(" ")}
            />
            <Row label="Date of birth" value={lead?.dateOfBirth ?? ""} />
            <Row label="Nationality" value={lead?.nationality ?? ""} />
            <Row
              label="Passport"
              value={
                lead?.passportNumber
                  ? `${lead.passportNumber}${lead.passportExpiry ? ` · expires ${lead.passportExpiry}` : ""}`
                  : "On file"
              }
            />
          </dl>
          {companions.length > 0 ? (
            <p className="mt-[12px] mb-0 text-[13px] text-[var(--fra-muted)]">
              Travelling with {companions.length} other{companions.length > 1 ? "s" : ""}:{" "}
              {companions.map((c) => `${c.firstName} ${c.lastName}`).join(", ")}.
            </p>
          ) : null}

          {/*
            The passport confirmation, verbatim from the overlay's.
            `requestApprovalSchema` requires `confirmed === true`, and before
            this existed NOTHING on this page was bound to it — so Submit
            failed validation on a field with no control, which renders as the
            button doing nothing at all. A silent dead button is the worst
            possible failure, so the error below is loud and the box is right
            under the details it is about.

            This is not the "passport step" LEIS-966 removes: that is about
            COLLECTING passport details, which step 2 does. This is the
            employee confirming what they are filing.
          */}
          <div
            className={`mt-[14px] rounded-xl border px-3.5 py-[12px] ${
              errors.confirmed
                ? "border-[var(--fra-rejected)] bg-[var(--fra-rejected-bg)]"
                : "border-[var(--fra-border)]"
            }`}
          >
            <label htmlFor="confirmed" className="flex cursor-pointer items-start gap-[12px]">
              <input
                id="confirmed"
                type="checkbox"
                {...register("confirmed")}
                aria-invalid={Boolean(errors.confirmed)}
                aria-describedby={errors.confirmed ? "confirmed-error" : undefined}
                className="mt-0.5 size-[18px] shrink-0 cursor-pointer accent-[var(--fra-navy-2)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-coral)]"
              />
              <span className="text-[13px] leading-relaxed text-[var(--fra-text)]">
                I confirm the details above exactly match each traveller&rsquo;s passport. I
                understand that wrong or missing details may stop us from flying, and any cost
                to fix them may not be covered.
              </span>
            </label>
            {errors.confirmed ? (
              <p
                id="confirmed-error"
                className="mt-2 pl-[30px] text-[13px] font-medium text-[var(--fra-rejected)]"
              >
                {errors.confirmed.message}
              </p>
            ) : null}
          </div>
        </FraSection>

        {/* 2 · Business information — the only thing typed on this page. */}
        <BusinessInfoSection
          step={2}
          register={register}
          errors={errors}
          meetingTypes={meetingTypesQuery.data ?? []}
          meetingTypesLoading={meetingTypesQuery.isPending}
          meetingTypesFailed={meetingTypesQuery.isError}
          onRetryMeetingTypes={() => void meetingTypesQuery.refetch()}
          additionalCost={{
            amount: bagCost.toFixed(2),
            note:
              extraBags > 0
                ? `${extraBags} extra checked bag${extraBags > 1 ? "s" : ""} from step 3.`
                : "No add-ons were chosen on step 3.",
          }}
        />

        {/* 3 · Travel policy */}
        <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>

        {/*
          `gap-[10px]`, not a bare stack. Each FraTotalRow is its own bordered,
          filled box; with nothing between them their borders meet and the two
          figures read as one block with a line through it. The overlay never
          hit this because it shows a single row — this pane is the first place
          that stacks them.
        */}
        <div className="flex flex-col gap-[10px] pt-[16px]">
          <FraTotalRow label="Fare" value={money(fare, currencySymbol)} />
          {bagCost > 0 ? (
            <FraTotalRow label="Additional cost" value={money(bagCost, currencySymbol)} />
          ) : null}
          <FraTotalRow label="Total (est.)" value={money(total, currencySymbol)} />
          <p className="mb-0 text-[12px] text-[var(--fra-muted)]">
            Re-priced when your admin approves, so the final amount can differ.
          </p>
        </div>

        {/*
          Hidden, exactly like step 2's. The sticky rail owns Back and Continue
          for all four steps and presses this through requestSubmit(), so a
          second VISIBLE submit here would be two buttons doing one thing —
          and the one further from the total is the one people would miss.
          Kept in the DOM rather than removed: it is what makes Enter submit
          the form, and what the rail presses.
        */}
        <button
          type="submit"
          className="hidden"
          aria-hidden="true"
          tabIndex={-1}
          disabled={submitting}
        />
      </form>
    </div>
  );
}
