"use client";

import { useCallback, useMemo, useState } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import type { FieldErrors, Resolver } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { defaultCountries, parseCountry } from "react-international-phone";

import { toast } from "@/lib/toast";
import { useBusinessSession } from "@/components/employee-requests/use-session";
import { useRequestTraveller } from "@/components/employee-requests/useRequestTraveller";
import {
  createTravelerDetailsSchema,
  type TravelerDetailsFormData,
} from "@/services/flights/traveler-details.schema";
import type {
  FlightReviewViewModel,
  FlightTravelerFormConfig,
} from "@/services/flights/types";
import {
  isAdultLike,
  minPassportExpiryIso,
  travelerCountSummary,
} from "@/services/flights/travelers";
import { airportsFromSegments } from "@/services/employee-requests/booking-for";
import { ISO_COUNTRIES, ISO_COUNTRY_CODES } from "@/constants/iso-countries";
import ContactCard from "./traveler/ContactCard";
import TravelerCard from "./traveler/TravelerCard";
import { collectTravelerErrors } from "./traveler/travelerErrorAnchors";

/**
 * Step 2 of the flight request — Traveler Details (LEIS-964).
 *
 * Adapted from leisure-ui's pane of the same name. The form itself, its
 * schema, its cards and its error handling are unchanged; what differs is
 * where the values come from and where they go.
 *
 * ── Prefill ────────────────────────────────────────────────────────────────
 *
 * Passenger 1 is the person the request is FOR — the signed-in employee, or
 * the colleague named by `bookingFor`. Their details come from the Business
 * API, through the same `useRequestTraveller` hook the request overlay uses,
 * so the two screens cannot disagree about who is travelling:
 *
 *   self       GET /business/profile
 *   colleague  GET /business/travellers/:id
 *
 * Both return the same field set — passport number and mobile included — so a
 * colleague prefills exactly as the employee does and the requester can
 * correct anything for this one request (LEIS-964; Bhupesh, 2026-10-09). The
 * colleague endpoint used to withhold the number; reading one is now
 * audit-logged server-side.
 *
 * Passengers 2..N are companions — people with no account of their own, typed
 * in for this trip. Nothing prefills them. The count comes from the fare: an
 * Amadeus offer is priced for the exact party searched for, so `config.slots`
 * is the authority on how many cards there are and what type each one is.
 *
 * ── Where the values go ────────────────────────────────────────────────────
 *
 * Nowhere, yet. LEIS-964: "Edits here never update the saved traveler profile"
 * — they become the request's `traveler_profile_snapshot` at submit and
 * nothing else. So three things leisure-ui does on this step are deliberately
 * absent:
 *
 *   no co-traveller writes   there is no "save for next time"; see TravelerCard
 *   no profile prefill cache leisure-ui POSTs the form to Redis via
 *                            saveFlightReviewGuests so a reload restores it.
 *                            That would put passport numbers into
 *                            search-service's booking cache for a request that
 *                            may never be approved. Step state survives moving
 *                            between steps because every pane stays mounted; a
 *                            hard reload loses it, same as the bag picks, and
 *                            one draft covering both lands with LEIS-965.
 *   no sign-in banner        reaching this page at all requires a business
 *                            session.
 */

/**
 * Above this many passengers the cards get a collapse control. At or below it
 * they stay open, which is how Agoda and every other OTA lays out the common
 * one-to-four passenger form — collapsing a two-passenger form hides half the
 * page behind a click for no benefit.
 */
const COLLAPSE_THRESHOLD = 4;

/** Fixed id so a second Continue replaces the first toast instead of stacking. */
const TRAVELER_FORM_TOAST_ID = "traveler-details-incomplete";

const EMPTY_TRAVELER_CONFIG: FlightTravelerFormConfig = {
  slots: [],
  documentRequired: false,
  dateOfBirthRequired: true,
  genderRequired: true,
  emailRequired: true,
  phoneRequired: true,
  residenceRequired: false,
};

/**
 * Common real-world spellings that don't exactly equal this list's own
 * canonical name — profiles created before signup/profile-edit switched to a
 * country dropdown could hold any of these from free-typing. Not exhaustive,
 * just the ones an English-language form reliably produces.
 */
const COUNTRY_ALIASES: Record<string, string> = {
  usa: "US",
  "us of a": "US",
  "united states of america": "US",
  "u.s.a": "US",
  "u.s.": "US",
  america: "US",
  uk: "GB",
  "u.k.": "GB",
  "great britain": "GB",
  britain: "GB",
  "england": "GB",
  "south korea": "KR",
  "republic of korea": "KR",
  "north korea": "KP",
  "czech republic": "CZ",
  "uae": "AE",
  "u.a.e.": "AE",
  "ivory coast": "CI",
  "cote d'ivoire": "CI",
  burma: "MM",
  "republic of ireland": "IE",
};

/**
 * A country as the business profile stores it, as the traveller form needs it.
 *
 * The two halves of Business mode disagree on this and it is invisible until a
 * form silently fails to prefill. `business_traveler_profiles` holds NAMES —
 * "India", "United States" — because that is what its own signup form collects.
 * The flight traveller form is leisure-ui's, and its country controls are keyed
 * on ISO codes ("IN", "US"); the schema even uppercases them on the way out.
 *
 * So a profile nationality of "India" matched no option, the combobox rendered
 * empty, and the employee was told to "Please select a nationality" for a field
 * their profile had already answered. Measured against the real API.
 *
 * Matched case-insensitively on the name, and a value that is ALREADY a code is
 * passed through — so this keeps working if profiles ever start storing codes.
 * A short alias table catches the handful of spellings ("USA", "UK") that a
 * free-text field reliably produced before it became a dropdown. An
 * unrecognised country returns "", which is the honest answer: better an
 * empty required field than a wrong country on a passport record.
 */
function isoCodeForCountry(value: string | null | undefined): string {
  const raw = (value ?? "").trim();
  if (!raw) return "";
  const upper = raw.toUpperCase();
  if (upper.length === 2 && ISO_COUNTRY_CODES.has(upper)) return upper;
  const lower = raw.toLowerCase();
  const match = ISO_COUNTRIES.find((c) => c.name.toLowerCase() === lower);
  if (match) return match.code;
  return COUNTRY_ALIASES[lower] ?? "";
}

/**
 * The profile's gender narrowed to what the form offers.
 *
 * Account setup (`YourDetailsStep.tsx`) stores the single-letter code 'M'/'F';
 * the separate profile-edit screen stores the full word 'Male'/'Female' (plus
 * a third option, 'Unspecified (X)', that this form has no slot for). Both
 * reach this prefill as whatever string the profile API echoed back, so a
 * plain lowercase-and-membership check only ever matched the full-word form —
 * every traveller whose profile still held the signup-era 'M'/'F' code (the
 * common case, since most profiles are never separately edited) rendered with
 * neither radio selected. Matched case-insensitively on both shapes.
 */
function formGender(
  value: string | null | undefined
): TravelerDetailsFormData["travelers"][number]["gender"] {
  const str = (value ?? "").trim().toLowerCase();
  if (str === "m" || str === "male") return "male";
  if (str === "f" || str === "female") return "female";
  return "";
}

/** "+91" for "in" — seeds the dial code so an untouched phone field is not
 *  reported as "Country code is required" on submit. */
function dialCodeFor(iso2: string): string {
  const match = defaultCountries.find((entry) => parseCountry(entry).iso2 === iso2);
  const dial = match ? parseCountry(match).dialCode : "1";
  return `+${dial}`;
}

/**
 * Every airport on the itinerary, for the colleague eligibility re-check.
 *
 * The whole itinerary, not an origin/destination pair: one leg crossing a
 * border makes the entire trip international, and that decides which policy
 * tab's Colleague booking toggle applies. Read off the priced offer's own
 * segments — `FlightEndpoint.iataCode` is a real IATA code, unlike
 * `FlightLegData.departure.airport`, which is a city name.
 */
function itineraryAirports(review: FlightReviewViewModel | undefined): string[] {
  const segments = (review?.itineraries ?? []).flatMap((itinerary) =>
    (itinerary.segments ?? []).map((segment) => ({
      from: segment.departure?.iataCode ?? "",
      to: segment.arrival?.iataCode ?? "",
      date: "",
    }))
  );
  return airportsFromSegments(segments);
}

export default function PaneTravelerDetails({
  review,
  bookingFor = null,
  draftTravelers,
}: {
  review?: FlightReviewViewModel;
  /** The colleague this request is for, or null for the employee themselves. */
  bookingFor?: string | null;
  /**
   * What this form last validated, restored after a reload — see
   * services/employee-requests/request-draft.ts. Wins over the profile
   * prefill, because it is what the employee actually typed, including any
   * correction they made to a prefilled value.
   */
  draftTravelers?: TravelerDetailsFormData;
}) {
  const baseConfig = review?.travelers ?? EMPTY_TRAVELER_CONFIG;
  const session = useBusinessSession();
  const airports = useMemo(() => itineraryAirports(review), [review]);

  const traveller = useRequestTraveller({
    travelerId: bookingFor,
    airports,
    sessionEmail: session?.email ?? "",
    enabled: baseConfig.slots.length > 0,
  });

  /**
   * No `storedPassportTravelerIds` override of our own.
   *
   * An earlier cut added the lead slot to that list when the traveller was a
   * colleague, because the API withheld their passport number and an empty
   * field would otherwise have failed validation. The detail endpoint now
   * returns it (LEIS-964), so every traveller's number is prefilled into an
   * ordinary editable field and there is nothing to exempt. Whatever
   * search-service puts in this list for its own reasons is still honoured.
   */
  const config = baseConfig;

  const profile = traveller.profile;

  /**
   * Remounts the FORM when the prefill source changes.
   *
   * React Hook Form reads `defaultValues` exactly once, at mount. The
   * traveller's profile arrives from a query, so on first render it is null
   * and the form initialises empty; when it lands, new `defaultValues` change
   * nothing. The fix is to remount, and the fix has to be applied to the
   * component that OWNS `useForm` — which is why the form lives in its own
   * component below rather than in this one.
   *
   * It was `key` on an inner <div> for a while, which looks identical and is
   * not: that remounted the fields while `useForm` carried on holding the
   * empty values it was born with. Measured against the real API, every
   * profile field came through blank and only the email — read synchronously
   * from the JWT — was filled in.
   *
   * A `key` rather than `reset()` in an effect: it is the house pattern for
   * this (see the overlay), and it clears touched/dirty state with it instead
   * of leaving a form that believes it has been edited.
   */
  const prefillKey = `${traveller.isSelf ? "self" : bookingFor}:${
    draftTravelers ? "draft" : profile ? "loaded" : traveller.isLoading ? "loading" : "none"
  }`;

  if (!config.slots.length) {
    return (
      <div className="fb-pane">
        <div className="bgColor-white shadow-sm p-4 rounded-3">
          <h3 className="subHeading fw-bold mb-2">Traveller details unavailable</h3>
          <p className="text-sm mb-0">
            Passenger information for this fare is missing. Go back and select the flight
            again.
          </p>
        </div>
      </div>
    );
  }

  return (
    <TravelerDetailsForm
      key={prefillKey}
      review={review}
      config={config}
      traveller={traveller}
      sessionEmail={session?.email ?? ""}
      bookingFor={bookingFor}
      draftTravelers={draftTravelers}
    />
  );
}

/**
 * The form itself. Mounted fresh whenever its prefill source changes — see
 * `prefillKey` above, which is the whole reason this is a separate component.
 */
function TravelerDetailsForm({
  review,
  config,
  traveller,
  sessionEmail,
  bookingFor,
  draftTravelers,
}: {
  review?: FlightReviewViewModel;
  config: FlightTravelerFormConfig;
  traveller: ReturnType<typeof useRequestTraveller>;
  sessionEmail: string;
  bookingFor: string | null;
  draftTravelers?: TravelerDetailsFormData;
}) {
  const schema = useMemo(() => createTravelerDetailsSchema(config), [config]);
  const profile = traveller.profile;
  const phoneCountry = "us";

  const defaultValues = useMemo<TravelerDetailsFormData>(
    () => ({
      travelers: config.slots.map((slot, index) => {
        // A restored draft is what the employee typed, so it beats the profile
        // for EVERY passenger — including corrections they made to a prefilled
        // value. Matched by travelerId rather than position, so a draft written
        // against a different party shape cannot shuffle passengers.
        const saved = draftTravelers?.travelers.find((t) => t.travelerId === slot.travelerId);
        if (saved) return saved;
        // Only passenger 1 is a known person; the rest are companions typed in.
        const lead = index === 0 ? profile : null;
        const nationality = isoCodeForCountry(lead?.nationality);
        return {
          travelerId: slot.travelerId,
          travelerType: slot.travelerType,
          firstName: lead?.firstName ?? "",
          lastName: lead?.lastName ?? "",
          hasNoLastName: false,
          dateOfBirth: lead?.dateOfBirth ?? "",
          gender: formGender(lead?.gender),
          associatedAdultId: slot.associatedAdultId || "",
          // Blank for a colleague on purpose — the API does not return their
          // number and the submit uses the one on their profile.
          passportNumber: lead?.passportNumber ?? "",
          passportExpiry: lead?.passportExpiry ?? "",
          // Mapped, not copied — see isoCodeForCountry.
          nationality,
          issuingCountry: isoCodeForCountry(lead?.passportIssuingCountry),
          // Business mode collects no residence field anywhere (signup, profile
          // edit) for this to come from — nationality is the closest honest
          // guess and the common case regardless, so default to it rather than
          // make the employee answer a question their profile already implies.
          countryOfResidence: nationality,
          savedTravellerId: "",
          saveToAccount: false,
        };
      }),
      contact: draftTravelers?.contact ?? {
        // The traveller's own work email, not the requester's: the e-ticket and
        // every delay alert go to the person flying.
        email: traveller.workEmail || sessionEmail || "",
        // Null for a colleague — the travellers endpoint returns no mobile, so
        // the requester supplies a number to reach them on.
        phone: profile?.mobileNumber ?? "",
        countryCode: profile?.mobileCountryCode || dialCodeFor(phoneCountry),
      },
    }),
    // This component is remounted when any of these would change — see
    // prefillKey in the wrapper — so the list is belt and braces.
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [config.slots, profile, traveller.workEmail, sessionEmail, draftTravelers]
  );

  const { register, control, handleSubmit, setValue, formState } =
    useForm<TravelerDetailsFormData>({
      resolver: zodResolver(schema) as Resolver<TravelerDetailsFormData>,
      defaultValues,
      // Validate a field when the employee leaves it, never while typing —
      // premature inline validation makes people second-guess an entry they
      // have not finished. Once a field has failed, re-check on change so the
      // message clears as soon as it is fixed rather than at the next blur.
      mode: "onTouched",
      reValidateMode: "onChange",
      // The error summary takes focus instead; letting RHF also focus the
      // first bad control would move focus twice and announce neither.
      shouldFocusError: false,
    });

  const { fields } = useFieldArray({ control, name: "travelers" });

  const adultSlots = useMemo(
    () => config.slots.filter((slot) => isAdultLike(slot.travelerType)),
    [config.slots]
  );
  const minPassportExpiry = useMemo(
    () => minPassportExpiryIso(config.lastArrivalAt),
    [config.lastArrivalAt]
  );
  const summary = travelerCountSummary(config.slots);

  const collapsible = config.slots.length > COLLAPSE_THRESHOLD;
  const [collapsed, setCollapsed] = useState<ReadonlySet<number>>(() => new Set());
  const toggleCard = useCallback((index: number) => {
    setCollapsed((prev) => {
      const next = new Set(prev);
      if (next.has(index)) next.delete(index);
      else next.add(index);
      return next;
    });
  }, []);

  /**
   * Reached only when the schema passes.
   *
   * Nothing is written anywhere — the values go to the orchestrator, which
   * holds them for step 4's snapshot. That is the whole of LEIS-964's "edits
   * are saved on the request snapshot only".
   */
  function onValid(data: TravelerDetailsFormData) {
    document.dispatchEvent(new CustomEvent("traveler-form-valid", { detail: data }));
  }

  /**
   * Continue was pressed with something missing.
   *
   * The fields carry the detail themselves — red border, inline message,
   * `aria-describedby` — so this only has to say that something is wrong and
   * put the employee in front of the first one. A single error names itself,
   * because at that point the count is less useful than the actual problem.
   */
  function onInvalid(errors: FieldErrors<TravelerDetailsFormData>) {
    const found = collectTravelerErrors(errors, config.slots);

    // A collapsed card cannot show its own error, and focus cannot move to a
    // control that is not in the tree. Open anything that failed first.
    if (collapsible) {
      const failed = new Set<number>();
      config.slots.forEach((_, index) => {
        if (errors.travelers?.[index]) failed.add(index);
      });
      if (failed.size > 0) {
        setCollapsed((prev) => {
          const next = new Set(prev);
          for (const index of failed) next.delete(index);
          return next;
        });
      }
    }

    const first = found[0];
    toast.error(
      found.length === 1 && first
        ? `${first.owner}: ${first.message}`
        : `${found.length} details still need your attention. The highlighted fields show what is missing.`,
      { id: TRAVELER_FORM_TOAST_ID }
    );

    if (!first) return;
    // After the collapse state above has been applied, so the target exists.
    requestAnimationFrame(() => {
      const target = document.getElementById(first.fieldId);
      target?.focus({ preventScroll: true });
      target?.scrollIntoView({ behavior: "smooth", block: "center" });
    });
  }

  const passengerCount = review?.travelerCount ?? config.slots.length;

  return (
    <div className="fb-pane">
      <form
        id="traveler-details-form"
        className="lf-form d-flex flex-column gap-3"
        onSubmit={(event) => {
          // Only our own submit. React bubbles a portal's events up the React
          // tree, so anything nested has already been handled by the form it
          // belongs to and must not run passenger validation.
          if (event.target !== event.currentTarget) {
            event.preventDefault();
            return;
          }
          void handleSubmit(onValid, onInvalid)(event);
        }}
        noValidate
      >
        {/* The server's verdict on whether this colleague can still be
            requested for on THIS itinerary — the same check that gated the
            Booking for dropdown, re-run here because a dropdown can be
            minutes stale. Explained, never hidden: "Esha is missing" and
            "Esha cannot be picked because colleague booking is off for
            international trips" are the same screen to someone who cannot
            see the second one. */}
        {!traveller.isLoading && !traveller.selectable ? (
          <div
            className="border border-color-warning-200 bgColor-warning-50 rounded-3 p-3"
            role="alert"
          >
            <p className="text-sm color-text-dark mb-0">
              {traveller.reasonMessage ??
                "This traveller cannot be requested for on this trip."}
            </p>
          </div>
        ) : null}

        {traveller.error ? (
          <div className="alert alert-danger py-2 px-3 text-sm mb-0" role="alert">
            {traveller.error.message}
          </div>
        ) : null}

        <p className="text-sm text-muted mb-0">
          This request is for{" "}
          <strong className="text-dark">
            {passengerCount} passenger{passengerCount === 1 ? "" : "s"}
          </strong>
          {summary ? ` (${summary})` : ""}. Enter each passenger&apos;s details exactly
          as they appear on their government-issued ID
          {config.documentRequired ? " or passport" : ""}.
        </p>

        {/* LEIS-964: editable for this request only. Said plainly, because the
            fields are prefilled from a profile and the obvious assumption
            about an edit is the wrong one. */}
        <p className="text-xs text-muted mb-0">
          Changes here apply to this request only — nobody&apos;s saved profile is
          updated.
        </p>

        <ContactCard
          control={control}
          register={register}
          setValue={setValue}
          defaultCountry={phoneCountry}
        />

        {fields.map((field, index) => {
          const slot = config.slots[index];
          if (!slot) return null;
          return (
            <TravelerCard
              key={field.id}
              index={index}
              slot={slot}
              config={config}
              control={control}
              register={register}
              setValue={setValue}
              adultSlots={adultSlots}
              minPassportExpiry={minPassportExpiry}
              collapsible={collapsible}
              expanded={!collapsed.has(index)}
              onToggle={() => toggleCard(index)}
            />
          );
        })}

        <button
          type="submit"
          style={{ display: "none" }}
          aria-hidden="true"
          tabIndex={-1}
          disabled={formState.isSubmitting}
        />
      </form>
    </div>
  );
}
