"use client";

import { Controller, useFormState, useWatch } from "react-hook-form";
import type { Control, UseFormRegister, UseFormSetValue } from "react-hook-form";
import {
  CountryCombobox,
  DateParts,
  Field,
  RadioGroup,
  TextField,
} from "@/components/ui/form";
import { isoCountrySelectOptions } from "@/constants/iso-countries";
import type { TravelerDetailsFormData } from "@/services/flights/traveler-details.schema";
import type {
  FlightTravelerFormConfig,
  FlightTravelerSlot,
} from "@/services/flights/types";
import {
  ADULT_INFANT_NAME_LIMIT,
  formatDateForMessage,
  isoDateOnly,
  normalizeTravelerName,
  travelerNameLength,
} from "@/services/flights/travelers";

const COUNTRY_OPTIONS = isoCountrySelectOptions().map((c) => ({
  code: c.code,
  name: c.name,
}));

const PASSPORT_OK = /^[A-Z0-9]{5,15}$/;

/** Whether search-service is already holding a passport for this traveller. */
function hasStoredPassport(ids: string[] | undefined, travelerId: string): boolean {
  return (ids ?? []).includes(travelerId);
}

/**
 * What an empty passport field is allowed to mean, said in the field itself.
 *
 * corp: two states, not leisure-ui's three — the server either already holds
 * this traveller's passport or it does not. The saved-traveller state is gone
 * with the picker.
 *
 * In Business mode the stored case is a COLLEAGUE: `GET /business/travellers/
 * :id` returns a passport's status and expiry but never its number, "not even
 * for the employee themselves", so the requester has nothing to prefill and
 * nothing to retype — the submit uses the number already on the colleague's
 * profile. The employee's own passport IS returned in full by
 * `GET /business/profile`, so their field is prefilled and this hint never
 * shows for them.
 *
 * The explanation matters: a blank required-looking field with no reason reads
 * as data lost, which is the bug this copy exists to prevent.
 */
function passportPlaceholder(storedPassport: boolean): string {
  if (storedPassport) return "On file — type to replace for this trip";
  return "As shown on the passport";
}

function passportHint(storedPassport: boolean): string | undefined {
  if (storedPassport) {
    return "Already on file for this traveller. Leave blank to use it, or type a number to request with a different document.";
  }
  return undefined;
}

/** The age rule, in the heading — where Agoda puts it, and where it is read. */
function typeCaption(slot: FlightTravelerSlot): string {
  switch (slot.travelerType) {
    case "CHILD":
      return "Child, 2–11 years";
    case "HELD_INFANT":
      return "Infant on lap, under 2 years";
    case "SEATED_INFANT":
      return "Infant with own seat, under 2 years";
    case "SENIOR":
      return "Senior, 60 years or older";
    case "YOUNG":
      return "Youth";
    case "STUDENT":
      return "Student";
    default:
      return "Adult, 12 years or older";
  }
}

function PersonIcon() {
  return (
    <svg
      width={18}
      height={18}
      viewBox="0 0 24 24"
      fill="none"
      strokeWidth={1.8}
      className="stroke-second"
      aria-hidden="true"
    >
      <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2" />
      <circle cx={12} cy={7} r={4} />
    </svg>
  );
}

export interface TravelerCardProps {
  index: number;
  slot: FlightTravelerSlot;
  config: FlightTravelerFormConfig;
  control: Control<TravelerDetailsFormData>;
  register: UseFormRegister<TravelerDetailsFormData>;
  setValue: UseFormSetValue<TravelerDetailsFormData>;
  adultSlots: FlightTravelerSlot[];
  minPassportExpiry: string;
  /** Only above four passengers; below that the cards stay open, as Agoda's do. */
  collapsible: boolean;
  expanded: boolean;
  onToggle: () => void;
}

/*
 * corp: four props and two blocks are gone from leisure-ui's version of this
 * file — `savedTravellers`, `savedPassports`, `travelerCount`,
 * `canSaveToAccount`, `onTravellerUsed`, the <SavedTravellerPicker/> and the
 * "save this passenger to my account" checkbox.
 *
 * All five belong to Personal mode's co-traveller store, which Business mode
 * does not use: a corporate request's travellers are the employee (from their
 * business traveler profile) plus companions typed in for that one trip, and
 * LEIS-964 is explicit that nothing typed on this step may update any saved
 * record. Offering "save for next time" here would be a promise the backend
 * deliberately does not keep.
 *
 * `config.storedPassportTravelerIds` still works and is how a colleague's
 * passport — which is never sent to the browser — is accepted as already on
 * file; see PaneTravelerDetails.
 */

export default function TravelerCard({
  index,
  slot,
  config,
  control,
  register,
  setValue,
  adultSlots,
  minPassportExpiry,
  collapsible,
  expanded,
  onToggle,
}: TravelerCardProps) {
  // Scoped to this passenger, so typing in one card does not re-render the
  // other eight. Subscribing to `formState` at the form root — which is what
  // this component replaced — re-rendered every card on every keystroke.
  const { errors } = useFormState({
    control,
    name: `travelers.${index}` as const,
  });
  const fieldErrors = errors.travelers?.[index];

  const hasNoLastName = useWatch({
    control,
    name: `travelers.${index}.hasNoLastName` as const,
  });
  const passportNumber = useWatch({
    control,
    name: `travelers.${index}.passportNumber` as const,
  });
  // corp: read back so the expiry hint can tell a shortfall from a blank
  // field — see the hint on the expiry control below.
  const passportExpiry = useWatch({
    control,
    name: `travelers.${index}.passportExpiry` as const,
  });
  // corp: leisure-ui also watches savedTravellerId, firstName, lastName and
  // dateOfBirth here, solely to re-check a referenced saved passport against
  // the identity on the card. With the picker gone there is nothing to
  // re-check, so those four subscriptions are dropped rather than left
  // watching for no reader.

  const prefix = `travelers.${index}` as const;
  // A passport already held server-side. Its number is never sent to the
  // browser, so the field stays empty and says so — leaving it blank keeps
  // what is stored, and typing replaces it.
  // corp: `storedPassportTravelerIds` alone. leisure-ui also consults the
  // picked saved traveller's record; Business mode has no picker, and a
  // colleague's passport — the only one not sent to the browser — is flagged
  // through this same list by PaneTravelerDetails.
  const storedPassport = hasStoredPassport(
    config.storedPassportTravelerIds,
    slot.travelerId
  );
  const passportOnFile = storedPassport;
  const fieldId = (name: string) => `traveler-${index}-${name}`;
  const isLapInfant = slot.travelerType === "HELD_INFANT";
  const departureLabel = config.firstDepartureAt
    ? formatDateForMessage(isoDateOnly(config.firstDepartureAt))
    : "";

  const cardErrorCount = fieldErrors
    ? Object.values(fieldErrors).filter(Boolean).length
    : 0;

  return (
    <section
      className="bgColor-white shadow-sm rounded-3 p-3 p-md-4"
      aria-labelledby={`traveler-heading-${index}`}
    >
      <div className="d-flex align-items-start justify-content-between gap-3">
        <div className="min-w-0">
          <h3
            id={`traveler-heading-${index}`}
            className="smallHeading mb-1 d-flex align-items-center gap-2 flex-wrap"
            style={{ textTransform: "none" }}
          >
            <PersonIcon />
            Passenger {index + 1}
            <span className="text-muted fw-400 text-sm">({typeCaption(slot)})</span>
          </h3>
          <p className="text-xs text-muted mb-0" style={{ maxWidth: "62ch" }}>
            Details must match this passenger&apos;s passport or photo ID. Names cannot
            be changed once the trip is booked.
          </p>
        </div>

        {collapsible ? (
          <button
            type="button"
            className="btn btn-sm btn-link text-decoration-none flex-shrink-0 p-0"
            onClick={onToggle}
            aria-expanded={expanded}
            aria-controls={`traveler-body-${index}`}
          >
            {expanded ? "Hide" : "Edit"}
            {!expanded && cardErrorCount > 0 ? (
              <span className="ms-1 text-danger">({cardErrorCount})</span>
            ) : null}
          </button>
        ) : null}
      </div>

      <div id={`traveler-body-${index}`} className="mt-3" hidden={collapsible && !expanded}>
        <p className="lf-required-note mb-3">
          <span className="lf-required-star" aria-hidden="true">*</span> Required field
        </p>

        <input type="hidden" {...register(`${prefix}.travelerId`)} />
        <input type="hidden" {...register(`${prefix}.travelerType`)} />

        <div className="d-flex flex-column gap-3">
          <RadioGroup
            id={fieldId("gender")}
            legend="Gender"
            required
            options={[
              { value: "male", label: "Male" },
              { value: "female", label: "Female" },
            ]}
            registration={register(`${prefix}.gender`)}
            error={fieldErrors?.gender?.message}
          />

          <div className="row g-3 lf-rows">
            <div className="col-md-6">
              <TextField
                id={fieldId("firstName")}
                label="First and middle name"
                required
                placeholder="As shown on the passport"
                autoComplete={`section-traveler-${slot.travelerId} given-name`}
                autoCapitalize="words"
                spellCheck={false}
                error={fieldErrors?.firstName?.message}
                {...register(`${prefix}.firstName`)}
              />
            </div>
            <div className="col-md-6">
              <TextField
                id={fieldId("lastName")}
                label="Last name"
                required={!hasNoLastName}
                placeholder={hasNoLastName ? "Not applicable" : "As shown on the passport"}
                autoComplete={`section-traveler-${slot.travelerId} family-name`}
                autoCapitalize="words"
                spellCheck={false}
                disabled={!!hasNoLastName}
                error={fieldErrors?.lastName?.message}
                {...register(`${prefix}.lastName`)}
                footer={
                  <label className="lf-check mt-1">
                    <input
                      type="checkbox"
                      {...register(`${prefix}.hasNoLastName`, {
                        onChange: (event) => {
                          if (event.target.checked) {
                            setValue(`${prefix}.lastName`, "", {
                              shouldValidate: true,
                              shouldDirty: true,
                            });
                          }
                        },
                      })}
                    />
                    <span>This passenger has no last name</span>
                  </label>
                }
              />
            </div>
          </div>

          <div className="row g-3 lf-rows">
            <div className="col-md-6">
              <Controller
                control={control}
                name={`${prefix}.dateOfBirth`}
                render={({ field }) => (
                  <DateParts
                    id={fieldId("dob")}
                    legend="Date of birth"
                    required
                    autoCompleteKind="bday"
                    value={field.value || ""}
                    onChange={field.onChange}
                    onBlur={field.onBlur}
                    error={fieldErrors?.dateOfBirth?.message}
                    hint={
                      departureLabel
                        ? `Age is checked on the departure date, ${departureLabel}.`
                        : undefined
                    }
                  />
                )}
              />
            </div>

            {config.documentRequired ? (
              <div className="col-md-6">
                <Controller
                  control={control}
                  name={`${prefix}.nationality`}
                  render={({ field }) => (
                    <CountryCombobox
                      id={fieldId("nationality")}
                      label="Nationality"
                      required
                      options={COUNTRY_OPTIONS}
                      value={field.value || ""}
                      onChange={field.onChange}
                      onBlur={field.onBlur}
                      error={fieldErrors?.nationality?.message}
                      // Matches DOB's own hint condition on this row (not just its
                      // text) — DOB only grows a hint line when departureLabel is
                      // set, and without one here too the two columns end at
                      // different heights whenever it is (effectively always on
                      // a real itinerary).
                      hint={departureLabel ? "As printed on your passport." : undefined}
                    />
                  )}
                />
              </div>
            ) : null}
          </div>

          {config.documentRequired ? (
            <>
              <div className="lf-section">
                <h4 className="lf-section-title">Passport details</h4>
                <div className="row g-3 lf-rows">
                  <div className="col-md-6">
                  <TextField
                    id={fieldId("passport")}
                    label="Passport number"
                    required={!passportOnFile}
                    uppercase
                    placeholder={passportPlaceholder(storedPassport)}
                    autoCapitalize="characters"
                    autoComplete="off"
                    spellCheck={false}
                    hint={
                      passportNumber ? undefined : passportHint(storedPassport)
                    }
                    showValid={
                      !fieldErrors?.passportNumber &&
                      (PASSPORT_OK.test((passportNumber || "").toUpperCase()) ||
                        (passportOnFile && !passportNumber))
                    }
                    error={fieldErrors?.passportNumber?.message}
                    {...register(`${prefix}.passportNumber`)}
                  />
                  </div>
                  <div className="col-md-6">
                  <Controller
                    control={control}
                    name={`${prefix}.issuingCountry`}
                    render={({ field }) => (
                      <CountryCombobox
                        id={fieldId("issuing")}
                        label="Country or region of issue"
                        required
                        options={COUNTRY_OPTIONS}
                        value={field.value || ""}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                        error={fieldErrors?.issuingCountry?.message}
                      />
                    )}
                  />
                  </div>
                  <div className="col-md-6">
                  <Controller
                    control={control}
                    name={`${prefix}.passportExpiry`}
                    render={({ field }) => (
                      <DateParts
                        id={fieldId("expiry")}
                        legend="Passport expiry date"
                        required
                        value={field.value || ""}
                        onChange={field.onChange}
                        onBlur={field.onBlur}
                        error={fieldErrors?.passportExpiry?.message}
                        /*
                         * corp (LEIS-964 / PRD §5): a WARNING, not a rule.
                         *
                         * leisure-ui blocks a passport with under six months
                         * left — correct for a booking, since the airline
                         * refuses boarding. This flow files a request a person
                         * reviews, and the PRD is explicit that the six-month
                         * check "shows a warning. It does not block
                         * submission." So the schema now blocks only on an
                         * already-expired passport, and this says the rest.
                         *
                         * Shown only once a date is actually entered that falls
                         * short: a hint that reads as a requirement is the
                         * thing being avoided.
                         */
                        hint={
                          passportExpiry && passportExpiry < minPassportExpiry
                            ? `Heads up: many countries want six months' validity beyond your trip. This expires before ${formatDateForMessage(
                                minPassportExpiry
                              )}. You can still send the request — your approver will see it.`
                            : `Most countries want it valid until at least ${formatDateForMessage(
                                minPassportExpiry
                              )}.`
                        }
                      />
                    )}
                  />
                  </div>
                </div>
              </div>
            </>
          ) : null}

          {config.residenceRequired ? (
            <div className="row g-3 lf-rows">
              <div className="col-md-6">
                <Controller
                  control={control}
                  name={`${prefix}.countryOfResidence`}
                  render={({ field }) => (
                    <CountryCombobox
                      id={fieldId("residence")}
                      label="Country or region of residence"
                      required
                      options={COUNTRY_OPTIONS}
                      value={field.value || ""}
                      onChange={field.onChange}
                      onBlur={field.onBlur}
                      error={fieldErrors?.countryOfResidence?.message}
                    />
                  )}
                />
              </div>
            </div>
          ) : null}

          {isLapInfant && adultSlots.length > 0 ? (
            <div className="row g-3 lf-rows">
              <div className="col-md-6">
                <Field
                  id={fieldId("adult")}
                  label="Travels on the lap of"
                  required
                  error={fieldErrors?.associatedAdultId?.message}
                >
                  {(a11y) => (
                    <select
                      {...a11y}
                      {...register(`${prefix}.associatedAdultId`)}
                      className={`lf-control ${
                        fieldErrors?.associatedAdultId ? "lf-control--invalid" : ""
                      }`}
                    >
                      <option value="">Select an adult</option>
                      {adultSlots.map((adult) => (
                        <option key={adult.travelerId} value={adult.travelerId}>
                          {adult.label}
                        </option>
                      ))}
                    </select>
                  )}
                </Field>
              </div>
              <div className="col-md-6 d-flex align-items-end">
                <LapInfantNameBudget control={control} index={index} />
              </div>
            </div>
          ) : null}
        </div>
      </div>
    </section>
  );
}

/**
 * The adult + lap-infant name budget, surfaced only once it is close to being
 * a problem.
 *
 * A permanent character counter on every name field would be noise — almost
 * nobody comes near 41 characters. Showing the remaining allowance from 80% of
 * the budget onwards means the constraint appears exactly when it starts to
 * matter, and the traveller can see the number move as they shorten a name
 * instead of only meeting it as a submit error.
 */
function LapInfantNameBudget({
  control,
  index,
}: {
  control: Control<TravelerDetailsFormData>;
  index: number;
}) {
  const travelers = useWatch({ control, name: "travelers" });
  const infant = travelers?.[index];
  const adult = travelers?.find(
    (t) => t?.travelerId && t.travelerId === infant?.associatedAdultId
  );
  if (!infant || !adult) return null;

  const used =
    travelerNameLength(
      normalizeTravelerName(infant.firstName || ""),
      normalizeTravelerName(infant.lastName || "")
    ) +
    travelerNameLength(
      normalizeTravelerName(adult.firstName || ""),
      normalizeTravelerName(adult.lastName || "")
    );

  if (used < ADULT_INFANT_NAME_LIMIT * 0.8) return null;
  const remaining = ADULT_INFANT_NAME_LIMIT - used;
  const over = remaining < 0;

  return (
    <p
      className="text-xs mb-0"
      style={{ color: over ? "var(--color-second-dark)" : "var(--color-content)" }}
      role="status"
    >
      {over
        ? `${Math.abs(remaining)} characters over the airline's limit for this infant and the adult they travel with.`
        : `${remaining} characters left in the shared name allowance for this infant and the adult they travel with.`}
    </p>
  );
}
