"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useFieldArray, useForm, useWatch } from "react-hook-form";
import { useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { Dialog } from "radix-ui";
import { AlertTriangle, Loader2, X } from "lucide-react";

import type { BusinessProfile } from "@/services/employee-login/employee-login.client";
import { useRequestTraveller } from "./useRequestTraveller";
import {
  getMeetingTypes,
  previewPolicy,
  submitFlightRequest,
} from "@/services/employee-requests/employee-requests.client";
import type {
  FlightOfferPayload,
  FlightSubmitRequestPayload,
  SubmittedRequest,
} from "@/services/employee-requests/employee-requests.types";
import { formatMoney } from "@/services/employee-requests/format";
import {
  blankCompanion,
  requestApprovalSchema,
  type RequestApprovalValues,
  type TravellerType,
} from "@/features/employee-requests/schemas/request-approval.schema";
import { rememberSubmittedRequest } from "@/services/employee-requests/submitted-handoff";

import { BusinessInfoSection } from "./BusinessInfoSection";
import { EmployeeSection } from "./EmployeeSection";
import { PolicyChecks, PolicyChecksSkeleton } from "./PolicyChecks";
import { SelectedFlightBand } from "./SelectedFlightBand";
import { TravelerDetailsSection } from "./TravelerDetailsSection";
import { SendCheckIcon, SendIcon } from "./send-icons";
import { useBusinessSession } from "./use-session";
import { FraSection, FraTotalRow, fraButton } from "./fra-primitives";

/**
 * The E4 request-approval overlay.
 *
 * Radix Dialog rather than a hand-rolled portal: this is a long, scrollable,
 * form-bearing modal, and focus trapping, Escape, scroll locking, restoring
 * focus to the trigger and the aria-modal wiring are all tedious to get right
 * and silently broken when they are not. corp already depends on `radix-ui`,
 * which is what shadcn's own Dialog is built on.
 *
 * Three structural decisions worth knowing before editing:
 *
 *   - **Nothing is reset here.** RequestApprovalHost gives this component a
 *     `key` per opened request, so a new request remounts it and the form, the
 *     banner, the queries and the idempotency key all start clean. Clearing
 *     them by hand was a second definition of "a fresh overlay", and a
 *     cascading render.
 *   - **The three reads are queries**, not hand-rolled loading state. Each used
 *     to begin with a synchronous setState inside the open effect.
 *   - **The policy preview is keyed on the offer**, never on the form. No field
 *     the employee types is an input to the evaluator, additional cost
 *     included, so re-running it on input would be pure traffic.
 */

/** Maps a server error `code` onto the field it belongs to. */
const FIELD_FOR_CODE: Partial<Record<string, keyof RequestApprovalValues>> = {
  UNKNOWN_MEETING_TYPE: "meetingType",
  INVALID_ADDITIONAL_COST: "additionalCost",
  PASSPORT_REQUIRED: "passportNumber",
  PASSPORT_EXPIRED: "passportExpiry",
};

/**
 * Codes meaning the offer itself is no longer requestable. Nothing the employee
 * can type fixes these, so they are stated as "search again" rather than pinned
 * to a field they would never think to look at.
 */
/** Party problems: the message names the traveller, so it reads as a banner. */
const PARTY_CODES = new Set([
  "TRAVELLER_COUNT_MISMATCH",
  "TOO_MANY_INFANTS",
  "INVALID_TRAVELLER_DOB",
  "TRAVELLER_PASSPORT_REQUIRED",
  "TRAVELLER_PASSPORT_EXPIRED",
]);

/**
 * The colleague is no longer a valid traveller for this trip (LEIS-934).
 *
 * Nothing typed in this overlay fixes any of them: the answer is to pick
 * somebody else, or to book for yourself — both of which happen on the search
 * bar, so these read as a banner with a way back rather than a field error.
 */
const COLLEAGUE_CODES = new Set([
  "COLLEAGUE_BOOKING_OFF",
  "COLLEAGUE_PROFILE_INCOMPLETE",
  "COLLEAGUE_PASSPORT_REQUIRED",
  "TRAVELLER_NOT_FOUND",
  "PASSPORT_NOT_YOURS",
  "INVALID_TRAVELLER",
]);

const STALE_OFFER_CODES = new Set([
  "DEPART_DATE_IN_PAST",
  "INVALID_DEPART_DATE",
  "RETURN_DATE_REQUIRED",
  "INVALID_RETURN_DATE",
  "RETURN_BEFORE_DEPART",
  "SEGMENTS_REQUIRED",
  "INVALID_SEGMENT",
  "INVALID_FARE",
  "UNSUPPORTED_CURRENCY",
]);

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

export interface RequestApprovalModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  offer: FlightOfferPayload | null;
  /** The kind of traveller in each seat the fare covers, traveller 1 first. */
  travellerTypes: TravellerType[];
  times?: { depart?: string; arrive?: string };
  /** PRD §6.1 "Booking for": null is the signed-in employee. */
  travelerId?: string | null;
  /** Every IATA code on the itinerary — the colleague check is per-tab. */
  airports?: string[];
}

export function RequestApprovalModal({
  open,
  onOpenChange,
  offer,
  travellerTypes,
  times,
  travelerId = null,
  airports = [],
}: RequestApprovalModalProps) {
  const router = useRouter();

  // Derived from the stored token rather than copied into state: it is already
  // an external store, and mirroring it meant a setState inside an effect.
  const session = useBusinessSession();
  const email = session?.email ?? "";

  const [banner, setBanner] = useState<{ text: string; action?: "search" } | null>(null);
  const [submitting, setSubmitting] = useState(false);

  /**
   * One key per opened draft, reused across every retry of it.
   *
   * Without it a double-tapped submit — or a retry after a timeout whose
   * response was lost on the way back — creates two requests with two FR
   * numbers and sends the approver two emails. Filled in lazily on first
   * submit; the component remounts per request, so a second request cannot
   * inherit this one's key.
   */
  const idempotencyKey = useRef<string>("");

  const enabled = open && Boolean(offer) && Boolean(session);

  /**
   * Who is travelling. The signed-in employee, or the colleague named by
   * `bookingFor` — one shape either way, so nothing below branches on which.
   */
  const traveller = useRequestTraveller({
    travelerId,
    airports,
    sessionEmail: email,
    enabled,
  });

  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,
    staleTime: 5 * 60_000,
  });

  const previewQuery = useQuery({
    // Keyed on what identifies the itinerary, not on the whole object: a fresh
    // `offerSnapshot.capturedAt` on every build would otherwise 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,
      travelerId ?? "self",
    ],
    queryFn: async () => {
      const res = await previewPolicy({
        type: "FLIGHT",
        offer: offer!,
        ...(travelerId ? { travelerId } : {}),
      });
      if (!res.success) {
        const err = new Error(res.message ?? "Could not check your travel policy.") as Error & {
          code?: string;
        };
        err.code = res.code;
        throw err;
      }
      return res.data!;
    },
    enabled,
    retry: false,
  });

  const profile: BusinessProfile | null = traveller.profile;
  const meetingTypes = useMemo(() => meetingTypesQuery.data ?? [], [meetingTypesQuery.data]);
  const preview = previewQuery.data ?? null;
  /**
   * Only ever true for a self-request. The server refuses a colleague with no
   * passport on file outright — nobody may type a passport into somebody
   * else's profile — so there is never a colleague's passport to collect here.
   */
  const needsPassport = preview?.trip.passportRequired ?? false;
  // Companions have no profile, so on an international trip they always type a
  // passport — unlike the employee, whose profile may already hold one.
  const needsCompanionPassport = preview?.trip.companionPassportRequired ?? false;
  /** What the fare was priced for, the employee included. */
  const expectedTravellers = offer?.travellers ?? 1;

  const previewCode = (previewQuery.error as (Error & { code?: string }) | null)?.code;

  /** The EMPLOYEE has no profile yet — nothing here can be submitted until they
   *  do, and the fix is a page they can reach. */
  const profileIncomplete = previewCode === "PROFILE_INCOMPLETE";

  /**
   * The chosen colleague cannot be requested for on this trip — the toggle went
   * off, they left the group or were deactivated, or they have no passport for
   * an international trip. Reported by the preview before the form is filled
   * in, and again by the submit if it changes in between.
   *
   * The fix is never something to type in this overlay, so it is stated as a
   * banner with a way back to the search bar rather than pinned to a field.
   */
  const travellerBlocked =
    traveller.reason !== null ||
    (previewCode !== undefined && COLLEAGUE_CODES.has(previewCode)) ||
    (traveller.error?.code !== undefined && COLLEAGUE_CODES.has(traveller.error.code));

  const travellerBlockedMessage =
    traveller.reasonMessage ??
    traveller.error?.message ??
    (previewQuery.error as Error | null)?.message ??
    "That colleague can no longer be requested for on this trip.";

  const {
    register,
    handleSubmit,
    setError,
    setFocus,
    control,
    formState: { errors },
  } = useForm<RequestApprovalValues>({
    resolver: zodResolver(
      requestApprovalSchema({
        needsPassport,
        needsCompanionPassport,
        departDate: offer?.departDate ?? "",
        expectedTravellers,
      })
    ),
    mode: "onTouched",
    defaultValues: {
      priority: "NORMAL",
      meetingType: "",
      justification: "",
      additionalCost: "",
      // One blank companion per seat the fare covers beyond the employee — and
      // each already set to the kind of traveller Amadeus priced for that seat,
      // rather than defaulting everyone to Adult. A family searching for two
      // adults and a child gets a child row without having to notice a dropdown,
      // and the age-band check then matches what they meant.
      //
      // Slot 0 is the employee, who is always an adult, so the companions are
      // the rest.
      travellers: travellerTypes
        .slice(1, Math.max(1, expectedTravellers))
        .map((type) => blankCompanion(type)),
    },
  });

  const companionArray = useFieldArray({ control, name: "travellers" });

  // `useWatch` rather than `watch()`: it subscribes to just these two fields
  // instead of the whole form, and — unlike `watch` — does not hand the React
  // Compiler a function it has to bail out of memoising this component on.
  const confirmed = useWatch({ control, name: "confirmed" }) === true;
  const additionalCostRaw = useWatch({ control, name: "additionalCost" });
  const companionValues = useWatch({ control, name: "travellers" });

  /**
   * The field array's stable keys married to the live values.
   *
   * `fields` holds the values as they were when the row was created, so using it
   * alone would leave every card headed "Traveller 2" however much was typed;
   * `useWatch` has the current values but no stable key for React. Each half
   * supplies what the other lacks.
   */
  const companions = useMemo(
    () =>
      companionArray.fields.map((field, i) => ({
        ...field,
        ...(companionValues?.[i] ?? {}),
        id: field.id,
      })),
    [companionArray.fields, companionValues]
  );

  const estTotal = useMemo(() => {
    if (!offer) return null;
    const extra = Number(additionalCostRaw);
    const add = Number.isFinite(extra) && extra > 0 ? extra : 0;
    return Math.round((offer.fare + add) * 100) / 100;
  }, [offer, additionalCostRaw]);

  // The one genuine side effect left: send an unauthenticated visitor to sign
  // in. It sets no state.
  useEffect(() => {
    if (!open || !offer || session) return;
    const next = `${window.location.pathname}${window.location.search}`;
    router.push(`/employee-login?next=${encodeURIComponent(next)}`);
  }, [open, offer, session, router]);

  const handleSubmitted = useCallback(
    (request: SubmittedRequest) => {
      // There is no GET /business/requests/:id, so the submitted screen can
      // only be rendered from this response. Stashed before navigating, keyed
      // by reference so a reload or a second tab still finds it.
      rememberSubmittedRequest(request);
      onOpenChange(false);
      router.push(`/employee-requests/submitted?ref=${encodeURIComponent(request.reference)}`);
    },
    [onOpenChange, router]
  );

  /**
   * The valid-submit handler.
   *
   * `handleSubmit(onValid)` is called in the form's onSubmit rather than during
   * render: building it during render puts a closure that reads
   * `idempotencyKey.current` into the render path, which the React Compiler
   * refuses — rightly, since a ref read during render is not something it can
   * reason about.
   */
  const onValid = useCallback(
    async (values: RequestApprovalValues) => {
      if (!offer || submitting) return;
      // Admins cannot file a request for approval; the server refuses them too.
      // Say so before sending, rather than after a round trip.
      if (session?.role === "ADMIN") {
        setBanner({
          text: "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);
      setBanner(null);

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

      const payload: FlightSubmitRequestPayload = {
        type: "FLIGHT",
        offer,
        ...(travelerId ? { travelerId } : {}),
        business: {
          meetingType: values.meetingType,
          justification: values.justification,
          client: values.client?.trim() || null,
          opportunity: values.opportunity?.trim() || null,
          additionalCost: values.additionalCost ? Number(values.additionalCost) : null,
          priority: values.priority,
        },
        travellers: values.travellers.map((t) => ({
          type: t.type,
          firstName: t.firstName.trim(),
          middleName: t.middleName?.trim() || null,
          lastName: t.lastName.trim(),
          gender: t.gender,
          dateOfBirth: t.dateOfBirth,
          // Sent only when the trip actually needs them: on a domestic trip
          // these are blank strings, and the API's nullable fields reject "".
          nationality: t.nationality?.trim() || null,
          passportNumber: t.passportNumber?.trim().toUpperCase() || null,
          passportExpiry: t.passportExpiry?.trim() || null,
          passportIssuingCountry: t.passportIssuingCountry?.trim() || null,
        })),
        ...(needsPassport && values.passportNumber
          ? {
              passport: {
                passportNumber: values.passportNumber.toUpperCase(),
                passportExpiry: values.passportExpiry!,
                passportIssuingCountry: values.passportIssuingCountry!,
                nationality: values.nationality!,
              },
            }
          : {}),
      };

      const res = await submitFlightRequest(payload, idempotencyKey.current);
      setSubmitting(false);

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

      // ── failure, routed by what the employee can actually do about it ──────
      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({ text: "Finish your traveller profile before requesting a trip." });
        return;
      }

      // The colleague stopped being a valid traveller between this overlay
      // opening and the submit — deactivated, moved group, or the toggle turned
      // off under them. Nothing in this form fixes it, so the way out is the
      // search bar.
      if (COLLEAGUE_CODES.has(code)) {
        setBanner({
          text: res.message ?? "That colleague can no longer be requested for on this trip.",
          action: "search",
        });
        return;
      }

      const field = FIELD_FOR_CODE[code];
      if (field) {
        setError(field, { type: "server", message: res.message });
        setFocus(field);
        // An admin can edit the company's meeting types between this overlay
        // opening and the submit, which is the only way a valid choice becomes
        // invalid — so refresh the list rather than leave a stale one on screen.
        if (code === "UNKNOWN_MEETING_TYPE") void meetingTypesQuery.refetch();
        return;
      }

      if (PARTY_CODES.has(code)) {
        // These already name the traveller they are about ("Traveller 3 needs
        // …"), which is more use than a red ring on one of thirty fields.
        setBanner({ text: res.message ?? "Check the traveller details and try again." });
        return;
      }

      if (STALE_OFFER_CODES.has(code)) {
        setBanner({
          text:
            res.message ?? "This flight can no longer be requested. Search again and pick another.",
          action: "search",
        });
        return;
      }

      setBanner({ text: res.message ?? "We could not send that request. Please try again." });
    },
    [
      offer,
      travelerId,
      submitting,
      needsPassport,
      router,
      setError,
      setFocus,
      meetingTypesQuery,
      handleSubmitted,
      session?.role,
    ]
  );

  if (!offer) return null;

  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal>
        <Dialog.Overlay className="data-[state=open]:animate-in data-[state=open]:fade-in-0 fixed inset-0 z-[1200] bg-black/50 backdrop-blur-[2px]" />
        <Dialog.Content
          // Scopes the Bootstrap-reboot reset in globals.css. The dialog is
          // portalled to document.body, which under /srp carries leisure-ui's
          // vendored stylesheets — so element-level rules reach it.
          data-corp-modal=""
          className="fixed top-1/2 left-1/2 z-[1201] flex max-h-[92svh] w-[calc(100vw-1.5rem)] max-w-[800px] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-[20px] bg-[var(--fra-surface)] text-[var(--fra-text)] shadow-[var(--fra-shadow-lg)] sm:w-[calc(100vw-3rem)]"
          aria-describedby="request-approval-desc"
          // The form is long and half-filled; a stray click outside should not
          // discard it. Escape and the explicit Cancel still close.
          onPointerDownOutside={(e) => e.preventDefault()}
          // Radix otherwise focuses the first tabbable element, which here is
          // the close button — so the overlay opened with a focus ring sitting
          // on "discard this". Focus the dialog itself instead: screen readers
          // still announce the title and description, the whole form is one Tab
          // away, and nothing is pre-aimed at the destructive control.
          onOpenAutoFocus={(e) => {
            e.preventDefault();
            (e.currentTarget as HTMLElement | null)?.focus();
          }}
          tabIndex={-1}
        >
          <header className="flex items-center gap-3.5 border-b border-[var(--fra-border)] px-6 py-[20px]">
            <span
              aria-hidden
              className="inline-flex size-11 shrink-0 items-center justify-center rounded-xl bg-[var(--fra-navy)] text-white"
            >
              <SendCheckIcon className="size-5" />
            </span>
            <div className="min-w-0 flex-1">
              <Dialog.Title className="m-0 mb-0.5 text-xl font-bold text-[var(--fra-heading)]">
                Request approval
              </Dialog.Title>
              <Dialog.Description
                id="request-approval-desc"
                className="text-[13px] text-[var(--fra-muted)]"
              >
                {traveller.isSelf || !traveller.name
                  ? "Add the business details and send this flight to your manager."
                  : `Add the business details and send ${traveller.name}'s flight to your manager.`}
              </Dialog.Description>
            </div>
            <Dialog.Close
              className="-m-2 inline-flex size-11 items-center justify-center rounded-full p-2 text-[var(--fra-muted)] transition-colors hover:bg-[var(--fra-hover)] hover:text-[var(--fra-text)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-coral)]"
              aria-label="Close without requesting"
            >
              <X className="size-5" />
            </Dialog.Close>
          </header>

          <form
            onSubmit={(e) => void handleSubmit(onValid)(e)}
            noValidate
            className="flex min-h-0 flex-1 flex-col"
          >
            <div className="min-h-0 flex-1 overflow-y-auto px-6 pt-2 pb-6">
              <SelectedFlightBand offer={offer} times={times} />

              {(banner || profileIncomplete || travellerBlocked) && (
                <div
                  role="alert"
                  className="mt-[16px] flex items-start gap-2.5 rounded-xl bg-[var(--fra-rejected-bg)] px-3.5 py-[12px] text-sm text-[var(--fra-rejected)]"
                >
                  <AlertTriangle aria-hidden className="mt-0.5 size-4 shrink-0" />
                  <div>
                    <p className="font-medium">
                      {banner?.text ??
                        (travellerBlocked
                          ? travellerBlockedMessage
                          : "Finish your traveller profile before you can request a trip.")}
                    </p>
                    {travellerBlocked && !banner && (
                      <button
                        type="button"
                        onClick={() => onOpenChange(false)}
                        className="mt-1 font-semibold underline underline-offset-2"
                      >
                        Back to results to choose someone else
                      </button>
                    )}
                    {profileIncomplete && !banner && (
                      <Link
                        href="/employee-profile"
                        className="mt-1 inline-block font-semibold underline underline-offset-2"
                      >
                        Go to your profile
                      </Link>
                    )}
                    {banner?.action === "search" && (
                      <button
                        type="button"
                        onClick={() => onOpenChange(false)}
                        className="mt-1 font-semibold underline underline-offset-2"
                      >
                        Back to results
                      </button>
                    )}
                  </div>
                </div>
              )}

              <EmployeeSection
                profile={profile}
                email={traveller.workEmail || email}
                isSelf={traveller.isSelf}
                travellerName={traveller.name}
              />

              <TravelerDetailsSection
                profile={profile}
                travellerIsSelf={traveller.isSelf}
                travellerName={traveller.name}
                passportStatus={traveller.passportStatus}
                needsPassport={needsPassport}
                needsCompanionPassport={needsCompanionPassport}
                companions={companions}
                expectedTravellers={expectedTravellers}
                onAdd={(type: TravellerType) => companionArray.append(blankCompanion(type))}
                onRemove={(index: number) => companionArray.remove(index)}
                register={register}
                errors={errors}
                confirmed={confirmed}
              />

              <BusinessInfoSection
                register={register}
                errors={errors}
                meetingTypes={meetingTypes}
                meetingTypesLoading={meetingTypesQuery.isPending}
                meetingTypesFailed={meetingTypesQuery.isError}
                onRetryMeetingTypes={() => void meetingTypesQuery.refetch()}
              />

              <FraSection step={4} title="Travel policy">
                <div aria-live="polite" aria-busy={previewQuery.isPending}>
                  {previewQuery.isPending && (
                    <>
                      <span className="sr-only">
                        Checking this trip against your travel policy…
                      </span>
                      <PolicyChecksSkeleton />
                    </>
                  )}
                  {preview && <PolicyChecks policy={preview.policy} warnings={preview.warnings} />}
                  {previewQuery.isError && !profileIncomplete && !travellerBlocked && (
                    <p className="flex items-start gap-2 text-[13px] text-[var(--fra-muted)]">
                      <AlertTriangle aria-hidden className="mt-0.5 size-4 shrink-0" />
                      We could not check your travel policy just now. You can still submit — it is
                      checked again when the request is filed, and being out of policy never blocks
                      it.
                    </p>
                  )}
                </div>

                {estTotal != null && (
                  <div className="mt-[12px]">
                    <FraTotalRow
                      label="Total (est.)"
                      value={formatMoney(estTotal, offer.currency)}
                    />
                  </div>
                )}
              </FraSection>
            </div>

            <div className="flex shrink-0 justify-end gap-2.5 border-t border-[var(--fra-border)] bg-[var(--fra-surface-2)] px-6 py-[16px]">
              <Dialog.Close className={`${fraButton.ghost} min-w-[116px]`} type="button">
                Cancel
              </Dialog.Close>
              <button
                type="submit"
                // A blocked colleague is the one failure the form cannot fix:
                // the server will refuse it whatever is typed, so the submit is
                // disabled rather than offered and then rejected.
                disabled={submitting || travellerBlocked || session?.role === "ADMIN"}
                className={`${fraButton.primary} min-w-[116px]`}
              >
                {submitting ? (
                  <>
                    <Loader2
                      aria-hidden
                      className="size-4 animate-spin motion-reduce:animate-none"
                    />
                    Sending…
                  </>
                ) : (
                  <>
                    <SendIcon className="size-4" />
                    Submit for approval
                  </>
                )}
              </button>
            </div>
          </form>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
