"use client";

import type { FieldErrors, UseFormRegister } from "react-hook-form";
import { AlertTriangle, BadgeCheck, IdCard, Plus, Trash2 } from "lucide-react";
import { cn } from "cn";

import { ISO_COUNTRIES } from "@/constants/iso-countries";
import type { BusinessProfile } from "@/services/employee-login/employee-login.client";
import { formatDate } from "@/services/employee-requests/format";
import {
  TRAVELLER_TYPES,
  TRAVELLER_TYPE_LABELS,
  type CompanionValues,
  type RequestApprovalValues,
  type TravellerType,
} from "@/features/employee-requests/schemas/request-approval.schema";
import { FraBadge, FraField, FraInput, FraSection, FraSelect, fraButton } from "./fra-primitives";

/**
 * Section 2 — everyone on the ticket, exactly as it will be issued.
 *
 * Traveller 1 is the employee and is **read-only**. The design draws every
 * field as an editable input, but POST /business/requests accepts no employee
 * details at all: their name, gender and date of birth are owned by the
 * traveller profile and change solely through POST /business/profile. Rendering
 * them editable would mean either dropping the edits on the floor or turning one
 * submit into two writes that can half-fail. Their values are shown as text
 * rather than disabled inputs — the design arrives at the same place
 * (`.emp-trav.is-verified .fra-input:disabled` strips the border and background
 * until it reads as plain text), and a disabled input is skipped by keyboard
 * navigation and often fails contrast, so a screen-reader user would be asked to
 * confirm details they cannot reach.
 *
 * Travellers 2..N are companions, typed in here because they have no profile
 * anywhere. Their passport numbers are reduced to the last four digits before
 * the server stores them, so this form is the only place the full number ever
 * exists.
 *
 * **How many there can be is decided by the fare, not by this form.** An
 * Amadeus offer is priced for the exact party the search asked for, so a fourth
 * person cannot be added to a fare quoted for three without re-pricing — the
 * server rejects a mismatch outright. Add traveller therefore fills the slots
 * the fare already covers and stops; going beyond is a new search.
 */

const GENDERS = ["Male", "Female", "Other"];

const EMPLOYEE_FIELDS: Array<{ key: keyof BusinessProfile; label: string; isDate?: boolean }> = [
  { key: "firstName", label: "First name" },
  { key: "middleName", label: "Middle name" },
  { key: "lastName", label: "Surname" },
  { key: "gender", label: "Gender" },
  { key: "dateOfBirth", label: "Date of birth", isDate: true },
  { key: "nationality", label: "Nationality" },
  { key: "passportNumber", label: "Passport number" },
  { key: "passportExpiry", label: "Passport expiry", isDate: true },
  { key: "passportIssuingCountry", label: "Issuing country" },
];

function ReadOnlyField({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <dt className="text-[13px] font-semibold text-[var(--fra-text)]">{label}</dt>
      <dd className="mt-1 text-sm font-semibold text-[var(--fra-heading)]">{value || "—"}</dd>
    </div>
  );
}

/** The card shell, shared so a companion and the employee read as one list. */
function TravellerCard({
  index,
  name,
  typeLabel,
  isEmployee,
  onRemove,
  children,
  invalid,
}: {
  index: number;
  name: string;
  typeLabel: string;
  isEmployee?: boolean;
  onRemove?: () => void;
  children: React.ReactNode;
  invalid?: boolean;
}) {
  return (
    <div
      className={cn(
        "rounded-[14px] border p-[16px] transition-colors",
        invalid
          ? "border-[var(--fra-rejected)]"
          : "border-[var(--fra-border)] bg-[var(--fra-surface)]"
      )}
    >
      <div className="mb-[12px] flex items-center gap-2.5">
        <span
          aria-hidden
          className="inline-flex size-[30px] shrink-0 items-center justify-center rounded-full bg-[var(--fra-navy-2)] text-[13px] font-bold text-white"
        >
          {index}
        </span>
        <div className="min-w-0 flex-1">
          <strong className="flex flex-wrap items-center gap-1.5 text-[15px] text-[var(--fra-heading)]">
            {name || `Traveller ${index}`}
            {isEmployee && (
              <span className="rounded-full bg-[var(--fra-blue-bg)] px-[7px] py-px text-[11px] font-bold text-[var(--fra-navy-2)]">
                You
              </span>
            )}
          </strong>
          <small className="block text-xs text-[var(--fra-muted)]">{typeLabel}</small>
        </div>
        {onRemove && (
          <button
            type="button"
            onClick={onRemove}
            className="inline-flex size-11 shrink-0 items-center justify-center rounded-lg text-[var(--fra-muted)] transition-colors hover:bg-[var(--fra-rejected-bg)] hover:text-[var(--fra-rejected)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--fra-coral)]"
          >
            <Trash2 aria-hidden className="size-4" />
            <span className="sr-only">Remove traveller {index}</span>
          </button>
        )}
      </div>
      {children}
    </div>
  );
}

export function TravelerDetailsSection({
  profile,
  travellerIsSelf = true,
  travellerName,
  passportStatus,
  needsPassport,
  needsCompanionPassport,
  companions,
  expectedTravellers,
  onAdd,
  onRemove,
  register,
  errors,
  confirmed,
}: {
  profile: BusinessProfile | null;
  /** False when a colleague's trip is being arranged (PRD §6.1). */
  travellerIsSelf?: boolean;
  /** Resolved name, used before the profile loads. */
  travellerName?: string;
  /**
   * "On file · expires Mar 2028", shown in place of a colleague's passport
   * NUMBER — which no endpoint returns for anybody else, and which nothing on
   * this screen needs: a colleague with no passport on file cannot be sent
   * abroad at all, so there is never one to collect here.
   */
  passportStatus?: string | null;
  /** The employee's own passport is missing and the trip is international.
   *  Only ever true on a self-request. */
  needsPassport: boolean;
  /** Companions always type a passport on an international trip. */
  needsCompanionPassport: boolean;
  companions: Array<CompanionValues & { id: string }>;
  /** What the fare was priced for, the employee included. */
  expectedTravellers: number;
  onAdd: (type: TravellerType) => void;
  onRemove: (index: number) => void;
  register: UseFormRegister<RequestApprovalValues>;
  errors: FieldErrors<RequestApprovalValues>;
  confirmed: boolean;
}) {
  const employeeName =
    [profile?.firstName, profile?.middleName, profile?.lastName].filter(Boolean).join(" ") ||
    travellerName ||
    "";

  const total = companions.length + 1;
  const remaining = expectedTravellers - total;
  const complete = remaining === 0;

  // The employee's passport fields move out of the read-only list and into the
  // form when they are being collected, so no value is ever shown twice.
  const employeeReadOnly = EMPLOYEE_FIELDS.filter(
    (f) =>
      !needsPassport ||
      !["passportNumber", "passportExpiry", "passportIssuingCountry", "nationality"].includes(
        f.key as string
      )
  );

  return (
    <FraSection
      step={2}
      title="Traveller details"
      note="as per passport"
      action={
        <FraBadge tone={complete && confirmed ? "approved" : "pending"}>
          {total} of {expectedTravellers} added
        </FraBadge>
      }
    >
      <div className="mb-3.5 flex gap-[12px] rounded-xl border border-[var(--fra-pending-border)] bg-[var(--fra-pending-bg)] px-3.5 py-[12px] text-[var(--fra-text)]">
        <AlertTriangle
          aria-hidden
          className="mt-0.5 size-[18px] shrink-0 text-[var(--fra-pending)]"
        />
        <div>
          <strong className="block text-sm text-[var(--fra-heading)]">
            Check every detail against the passport — you are responsible for it.
          </strong>
          <p className="mt-1 text-[13px] leading-relaxed text-[var(--fra-text)]">
            Each ticket is issued exactly as these details read. A name, date of birth, nationality
            or passport number that does not match the passport can get that traveller denied
            boarding, and fixing it after ticketing may need a new ticket.
          </p>
        </div>
      </div>

      <div className="grid gap-3.5">
        {/* ── Traveller 1: the employee ─────────────────────────────────── */}
        <TravellerCard
          index={1}
          name={employeeName}
          typeLabel={TRAVELLER_TYPE_LABELS.ADULT}
          isEmployee={travellerIsSelf}
        >
          <p className="mt-0 mb-[12px] flex items-center gap-1.5 text-xs text-[var(--fra-navy-2)]">
            <IdCard aria-hidden className="size-3.5 shrink-0" />
            {travellerIsSelf
              ? "From your traveller profile. To change any of it, edit your profile."
              : "From their traveller profile. Only they can change it."}
          </p>

          <dl className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-3">
            {employeeReadOnly.map(({ key, label, isDate }) => {
              const raw = profile?.[key];
              const value = typeof raw === "string" ? raw : "";
              // A colleague's passport number is never returned, so the number
              // row becomes a status row. Rendering the absent value would
              // print "—" beside a passport that is, in fact, on file.
              if (key === "passportNumber" && passportStatus) {
                return (
                  <ReadOnlyField key="passportNumber" label="Passport" value={passportStatus} />
                );
              }
              return (
                <ReadOnlyField
                  key={key as string}
                  label={label}
                  value={isDate ? formatDate(value) : value}
                />
              );
            })}
          </dl>

          {needsPassport && (
            <div className="mt-[16px] border-t border-dashed border-[var(--fra-border)] pt-[16px]">
              <p className="mb-[12px] flex items-start gap-1.5 text-[13px] text-[var(--fra-text)]">
                <BadgeCheck
                  aria-hidden
                  className="mt-0.5 size-4 shrink-0 text-[var(--fra-navy-2)]"
                />
                This trip leaves the country, and we do not have your passport yet. It is saved to
                your profile, so the next international trip will not ask again.
              </p>
              <div className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2">
                <FraField
                  id="nationality"
                  label="Nationality"
                  required
                  error={errors.nationality?.message}
                >
                  {(p) => (
                    <FraSelect {...p} {...register("nationality")} autoComplete="country-name">
                      <option value="">Select nationality</option>
                      {ISO_COUNTRIES.map((c) => (
                        <option key={c.code} value={c.name}>
                          {c.name}
                        </option>
                      ))}
                    </FraSelect>
                  )}
                </FraField>
                <FraField
                  id="passportNumber"
                  label="Passport number"
                  required
                  error={errors.passportNumber?.message}
                >
                  {(p) => (
                    <FraInput
                      {...p}
                      {...register("passportNumber")}
                      autoComplete="off"
                      spellCheck={false}
                      className="uppercase"
                    />
                  )}
                </FraField>
                <FraField
                  id="passportExpiry"
                  label="Passport expiry date"
                  required
                  error={errors.passportExpiry?.message}
                >
                  {(p) => <FraInput {...p} {...register("passportExpiry")} type="date" />}
                </FraField>
                <FraField
                  id="passportIssuingCountry"
                  label="Issuing country"
                  required
                  error={errors.passportIssuingCountry?.message}
                >
                  {(p) => (
                    <FraSelect {...p} {...register("passportIssuingCountry")}>
                      <option value="">Select issuing country</option>
                      {ISO_COUNTRIES.map((c) => (
                        <option key={c.code} value={c.name}>
                          {c.name}
                        </option>
                      ))}
                    </FraSelect>
                  )}
                </FraField>
              </div>
            </div>
          )}
        </TravellerCard>

        {/* ── Travellers 2..N: companions ───────────────────────────────── */}
        {companions.map((companion, i) => {
          const rowErrors = errors.travellers?.[i];
          const name = [companion.firstName, companion.lastName].filter(Boolean).join(" ");
          return (
            <TravellerCard
              key={companion.id}
              index={i + 2}
              name={name}
              typeLabel={TRAVELLER_TYPE_LABELS[companion.type]}
              onRemove={() => onRemove(i)}
              invalid={Boolean(rowErrors)}
            >
              <div className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-3">
                <FraField
                  id={`traveller-${i}-type`}
                  label="Traveller type"
                  required
                  error={rowErrors?.type?.message}
                >
                  {(p) => (
                    <FraSelect {...p} {...register(`travellers.${i}.type` as const)}>
                      {TRAVELLER_TYPES.map((t) => (
                        <option key={t} value={t}>
                          {TRAVELLER_TYPE_LABELS[t]}
                        </option>
                      ))}
                    </FraSelect>
                  )}
                </FraField>
                <FraField
                  id={`traveller-${i}-firstName`}
                  label="First name"
                  required
                  error={rowErrors?.firstName?.message}
                >
                  {(p) => (
                    <FraInput
                      {...p}
                      {...register(`travellers.${i}.firstName` as const)}
                      autoComplete="off"
                    />
                  )}
                </FraField>
                <FraField
                  id={`traveller-${i}-middleName`}
                  label="Middle name"
                  error={rowErrors?.middleName?.message}
                >
                  {(p) => (
                    <FraInput
                      {...p}
                      {...register(`travellers.${i}.middleName` as const)}
                      autoComplete="off"
                    />
                  )}
                </FraField>
                <FraField
                  id={`traveller-${i}-lastName`}
                  label="Surname"
                  required
                  error={rowErrors?.lastName?.message}
                >
                  {(p) => (
                    <FraInput
                      {...p}
                      {...register(`travellers.${i}.lastName` as const)}
                      autoComplete="off"
                    />
                  )}
                </FraField>
                <FraField
                  id={`traveller-${i}-gender`}
                  label="Gender"
                  required
                  error={rowErrors?.gender?.message}
                >
                  {(p) => (
                    <FraSelect {...p} {...register(`travellers.${i}.gender` as const)}>
                      <option value="">Select gender</option>
                      {GENDERS.map((g) => (
                        <option key={g} value={g}>
                          {g}
                        </option>
                      ))}
                    </FraSelect>
                  )}
                </FraField>
                <FraField
                  id={`traveller-${i}-dateOfBirth`}
                  label="Date of birth"
                  required
                  error={rowErrors?.dateOfBirth?.message}
                >
                  {(p) => (
                    <FraInput
                      {...p}
                      {...register(`travellers.${i}.dateOfBirth` as const)}
                      type="date"
                    />
                  )}
                </FraField>

                {needsCompanionPassport && (
                  <>
                    <FraField
                      id={`traveller-${i}-nationality`}
                      label="Nationality"
                      required
                      error={rowErrors?.nationality?.message}
                    >
                      {(p) => (
                        <FraSelect {...p} {...register(`travellers.${i}.nationality` as const)}>
                          <option value="">Select nationality</option>
                          {ISO_COUNTRIES.map((c) => (
                            <option key={c.code} value={c.name}>
                              {c.name}
                            </option>
                          ))}
                        </FraSelect>
                      )}
                    </FraField>
                    <FraField
                      id={`traveller-${i}-passportNumber`}
                      label="Passport number"
                      required
                      error={rowErrors?.passportNumber?.message}
                    >
                      {(p) => (
                        <FraInput
                          {...p}
                          {...register(`travellers.${i}.passportNumber` as const)}
                          autoComplete="off"
                          spellCheck={false}
                          className="uppercase"
                        />
                      )}
                    </FraField>
                    <FraField
                      id={`traveller-${i}-passportExpiry`}
                      label="Passport expiry date"
                      required
                      error={rowErrors?.passportExpiry?.message}
                    >
                      {(p) => (
                        <FraInput
                          {...p}
                          {...register(`travellers.${i}.passportExpiry` as const)}
                          type="date"
                        />
                      )}
                    </FraField>
                    <FraField
                      id={`traveller-${i}-passportIssuingCountry`}
                      label="Issuing country"
                      required
                      error={rowErrors?.passportIssuingCountry?.message}
                    >
                      {(p) => (
                        <FraSelect
                          {...p}
                          {...register(`travellers.${i}.passportIssuingCountry` as const)}
                        >
                          <option value="">Select issuing country</option>
                          {ISO_COUNTRIES.map((c) => (
                            <option key={c.code} value={c.name}>
                              {c.name}
                            </option>
                          ))}
                        </FraSelect>
                      )}
                    </FraField>
                  </>
                )}
              </div>
            </TravellerCard>
          );
        })}
      </div>

      {/* ── Add traveller ──────────────────────────────────────────────── */}
      <div className="mt-3.5">
        {remaining > 0 ? (
          <div className="flex flex-wrap items-center gap-[12px] rounded-xl border border-dashed border-[var(--fra-border-strong)] px-3.5 py-[12px]">
            <p className="min-w-0 flex-1 text-[13px] text-[var(--fra-muted)]">
              This fare covers{" "}
              <strong className="text-[var(--fra-text)]">{expectedTravellers}</strong> travellers.
              Add the {remaining === 1 ? "last one" : `remaining ${remaining}`} before submitting.
            </p>
            <div className="flex flex-wrap gap-2">
              {TRAVELLER_TYPES.map((type) => (
                <button
                  key={type}
                  type="button"
                  onClick={() => onAdd(type)}
                  className={cn(fraButton.ghost, "h-11")}
                >
                  <Plus aria-hidden className="size-4" />
                  Add {type.toLowerCase()}
                </button>
              ))}
            </div>
          </div>
        ) : (
          <p className="text-[13px] text-[var(--fra-muted)]">
            All {expectedTravellers} traveller{expectedTravellers === 1 ? "" : "s"} this fare covers
            {expectedTravellers === 1 ? " is" : " are"} listed. To travel with more people, search
            again for a larger party — the fare has to be quoted for everyone.
          </p>
        )}
        {errors.travellers?.message && (
          <p className="mt-2 text-[13px] font-medium text-[var(--fra-rejected)]">
            {errors.travellers.message}
          </p>
        )}
      </div>

      {/* ── Declaration ────────────────────────────────────────────────── */}
      <div
        className={cn(
          "mt-3.5 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>
        )}
      </div>
    </FraSection>
  );
}
