"use client";

import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { AlertCircle, Check, Search, UserRound } from "lucide-react";

import { useBusinessSession } from "@/components/employee-requests/use-session";
import { nameFromEmail } from "@/lib/business-session";
import type { BookableTraveller } from "@/services/employee-requests/travellers.client";
import { ChevronIcon } from "@/components/flights/v3/icons";
import { useBookableTravellers } from "./useBookableTravellers";

/**
 * PRD §6.1's **Booking for** control: who this trip is being requested for.
 *
 * ── Why this is not a shadcn Popover/Command combobox ─────────────────────
 *
 * It lives inside `FlightSearchFormV3`, whose six other fields share one
 * open-field slot (`openField`), one document click-away handler and one
 * `.fs-field > .fs-dropdown` positioning contract. A Radix Popover here would
 * bring a second outside-click owner and a second focus manager into that form,
 * and the two would fight: closing this panel would not close the calendar, and
 * the form's own handler would close this one mid-interaction.
 *
 * So the shell is the form's (the parent owns `open`), and the combobox
 * semantics are written out here rather than inherited: `aria-activedescendant`
 * on the search input, `role="option"` rows, arrow/Home/End/Enter/Escape keys.
 *
 * ── Why ineligible people are shown at all ────────────────────────────────
 *
 * A colleague who cannot be picked is rendered `aria-disabled` WITH the
 * server's reason, not filtered out. "Esha is missing" and "Esha cannot be
 * picked because her profile is incomplete" are the same screen to a user who
 * cannot see the second one — and the first sends them to ask the wrong
 * question. `aria-disabled` rather than `disabled` so the row stays reachable
 * by keyboard: the reason is the point.
 *
 * The ONE exception is Colleague booking being off for the trip's tab. LEIS-980
 * says "Booking for shows only the employee (Myself) for flights on that tab",
 * so the server withholds those rows entirely and sets `colleaguesHidden`. With
 * nobody to pick, this control is already inert by its own rule below — so the
 * explanation those rows would have carried moves to the field's sub-line,
 * which is the only part still on screen. Settled by Bhupesh on the ticket's
 * side on 2026-10-12.
 *
 * ── Spacing uses arbitrary values on purpose ──────────────────────────────
 *
 * This renders on /srp, where Bootstrap is loaded. Bootstrap and Tailwind share
 * `p-3`/`gap-3`/`py-4` with DIFFERENT scales and Bootstrap's carry
 * `!important`, which no cascade layer can beat. `p-[12px]` cannot collide.
 */

export interface BookingForFieldProps {
  /** Selected traveller id; null means the signed-in employee. */
  value: string | null;
  onChange: (travellerId: string | null) => void;
  /**
   * Every IATA code on the itinerary — decides the policy tab server-side.
   * Flights only; a hotel caller passes `countryCode` instead (LEIS-1042),
   * never both.
   */
  airports?: string[];
  /** The hotel property's ISO-2 country — mutually exclusive with `airports`.
   *  Pass `""` rather than omitting it once no destination is chosen yet, so
   *  the field still renders in hotel mode (ungated) instead of flight mode. */
  countryCode?: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** `compact` is the results-page bar, where the cell is ~134px wide. */
  variant?: "full" | "compact";
}

function Row({
  traveller,
  selected,
  active,
  id,
  onSelect,
  onHover,
}: {
  traveller: BookableTraveller;
  selected: boolean;
  active: boolean;
  id: string;
  onSelect: (traveller: BookableTraveller) => void;
  onHover: () => void;
}) {
  const disabled = !traveller.selectable;

  return (
    <li
      id={id}
      role="option"
      aria-selected={selected}
      aria-disabled={disabled || undefined}
      onMouseEnter={onHover}
      onClick={(e) => {
        e.stopPropagation();
        if (!disabled) onSelect(traveller);
      }}
      className={[
        // 44px floor: this is a touch target on the mobile search sheet.
        "flex min-h-[44px] cursor-pointer items-start gap-[10px] rounded-[10px] px-[10px] py-[8px]",
        active ? "bg-[#f1f5f9]" : "",
        disabled ? "cursor-not-allowed opacity-60" : "",
      ]
        .filter(Boolean)
        .join(" ")}
    >
      {/* The accent bar MakeMyTrip uses to mark the pickable rows. Decorative —
          every state it expresses is also written in text below. */}
      <span
        aria-hidden
        className={[
          "mt-[3px] h-[18px] w-[3px] shrink-0 rounded-full",
          disabled ? "bg-[#cfd6de]" : "bg-[var(--fra-coral,#f45d6b)]",
        ].join(" ")}
      />
      <span className="min-w-0 flex-1">
        <span className="flex items-center gap-[8px]">
          <span className="truncate text-[14px] leading-[18px] font-semibold text-[#1f2933]">
            {traveller.name}
          </span>
          {traveller.isSelf ? (
            <span className="shrink-0 rounded-[4px] bg-[#fdecef] px-[6px] py-[1px] text-[10px] font-bold tracking-wide text-[#d9434f] uppercase">
              Myself
            </span>
          ) : null}
        </span>
        <span className="mt-[2px] block truncate text-[12px] leading-[16px] text-[#6b7785]">
          {traveller.workEmail}
        </span>
        {disabled && traveller.reasonMessage ? (
          <span className="mt-[4px] flex items-start gap-[4px] text-[11px] leading-[15px] text-[#b45309]">
            <AlertCircle aria-hidden className="mt-[1px] size-[12px] shrink-0" />
            <span>{traveller.reasonMessage}</span>
          </span>
        ) : null}
      </span>
      {selected ? (
        <Check aria-hidden className="mt-[2px] size-[16px] shrink-0 text-[#16a34a]" />
      ) : null}
    </li>
  );
}

export function BookingForField({
  value,
  onChange,
  airports,
  countryCode,
  open,
  onOpenChange,
  variant = "full",
}: BookingForFieldProps) {
  const listboxId = useId();
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [search, setSearch] = useState("");
  const [activeId, setActiveId] = useState<string | null>(null);

  /**
   * Two reads of the same endpoint, and deliberately so.
   *
   * The unfiltered one names whoever is selected, so typing in the search box
   * cannot blank the field's own label. The filtered one is the panel's rows.
   * React Query caches them separately and the unfiltered call is made once.
   */
  const all = useBookableTravellers({ airports, countryCode });
  const filtered = useBookableTravellers({
    airports,
    countryCode,
    search,
    enabled: open && search !== "",
  });

  const rows = search !== "" ? filtered.travellers : all.travellers;
  const isSearching = search !== "" && filtered.isFetching && filtered.travellers.length === 0;

  const selected = useMemo(
    () =>
      value === null
        ? (all.travellers.find((t) => t.isSelf) ?? null)
        : (all.travellers.find((t) => t.businessUserId === value) ?? null),
    [all.travellers, value]
  );

  /**
   * The id the arrow keys are on.
   *
   * Derived rather than synchronised: when the rows change under it — a new
   * search term, a refetch — a stale `activeId` simply stops matching and the
   * first row takes over. An effect keeping the two in step would be a
   * `setState` inside an effect, which the React Compiler rejects in corp's own
   * code, and it would also fight the user mid-keystroke.
   */
  const activeIndex = Math.max(
    0,
    rows.findIndex((t) => t.businessUserId === activeId)
  );
  const activeRow = rows[activeIndex] ?? null;
  const optionId = useCallback(
    (travellerId: string) => `${listboxId}-opt-${travellerId}`,
    [listboxId]
  );

  // Focus the search box when the panel opens. A DOM call, not state — the
  // alternative is a user who has to click twice to start typing.
  useEffect(() => {
    if (open) inputRef.current?.focus();
  }, [open]);

  const close = useCallback(() => {
    setSearch("");
    setActiveId(null);
    onOpenChange(false);
  }, [onOpenChange]);

  const select = useCallback(
    (traveller: BookableTraveller) => {
      onChange(traveller.isSelf ? null : traveller.businessUserId);
      close();
    },
    [onChange, close]
  );

  const onKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLInputElement>) => {
      if (e.key === "Escape") {
        e.preventDefault();
        e.stopPropagation();
        close();
        return;
      }
      if (rows.length === 0) return;

      if (e.key === "ArrowDown" || e.key === "ArrowUp") {
        e.preventDefault();
        const next =
          e.key === "ArrowDown"
            ? (activeIndex + 1) % rows.length
            : (activeIndex - 1 + rows.length) % rows.length;
        setActiveId(rows[next]!.businessUserId);
        return;
      }
      if (e.key === "Home") {
        e.preventDefault();
        setActiveId(rows[0]!.businessUserId);
        return;
      }
      if (e.key === "End") {
        e.preventDefault();
        setActiveId(rows[rows.length - 1]!.businessUserId);
        return;
      }
      if (e.key === "Enter") {
        e.preventDefault();
        // Enter on a row that cannot be picked does nothing rather than
        // silently selecting the next one that can — the reason is on screen,
        // and quietly choosing somebody else is the worse answer.
        if (activeRow?.selectable) select(activeRow);
      }
    },
    [rows, activeIndex, activeRow, select, close]
  );

  const selfRow = all.travellers.find((t) => t.isSelf) ?? null;
  const colleagues = rows.filter((t) => !t.isSelf);

  /**
   * Before the list resolves — and when it cannot, because the session has
   * expired or the API is unreachable — the field still has to name somebody,
   * and the signed-in user is in the JWT. The alternative is a field that reads
   * "You" over an empty line on first paint, which is the one moment the
   * traveller most needs to see their own address.
   */
  const session = useBusinessSession();
  const sessionEmail = session?.email ?? "";
  const selectedLabel =
    selected?.name ??
    (value === null ? (sessionEmail ? nameFromEmail(sessionEmail) : "You") : "Unavailable");
  const selectedSub =
    selected?.workEmail ??
    (value === null ? sessionEmail : "This person can no longer be selected");
  const isUnresolved = value !== null && selected === null && !all.isLoading;

  /**
   * Why this field is inert, when the reason is the policy rather than the
   * employee simply having no colleagues (LEIS-980).
   *
   * The ticket says Booking for shows only Myself when the toggle is off, so
   * the server withholds the rows and there is nothing to open — which leaves
   * nowhere for the dropdown's empty state to say why. This sub-line is the
   * only place the explanation is still visible, and the alternative is a dead
   * control an employee has no way to understand. Their own email, which it
   * replaces, is the least useful thing this field can show.
   */
  const policySub =
    all.colleaguesHidden && value === null
      ? "Your group can’t book for colleagues on this trip"
      : null;

  /**
   * Nothing to choose from: the group is one person, or the toggle is off for
   * this trip. The control still renders — the traveller's name on the search
   * bar is useful, and a field that vanishes between searches is worse than one
   * that is quietly inert — but it does not pretend to be a dropdown.
   */
  const interactive = all.hasSession && (all.hasColleagues || all.isLoading || Boolean(all.error));

  return (
    <>
      <button
        type="button"
        className={
          variant === "compact" ? "fs-compact-trav-trigger" : "fs-trigger w-full text-left"
        }
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={`Booking for ${selectedLabel}. Change who this trip is for.`}
        disabled={!interactive}
        onClick={(e) => {
          e.stopPropagation();
          onOpenChange(!open);
        }}
        onKeyDown={(e) => {
          if (e.key === "ArrowDown" && !open) {
            e.preventDefault();
            onOpenChange(true);
          }
        }}
      >
        {variant === "compact" ? (
          <>
            <span className="fs-compact-label">Booking For</span>
            <span className="fs-compact-trav-value">
              <span className="truncate">{selectedLabel}</span>
            </span>
          </>
        ) : (
          <>
            <span className="fs-head">
              <span className="fs-label">
                <UserRound aria-hidden className="fs-ic" />
                Booking For
              </span>
              {interactive ? <ChevronIcon /> : null}
            </span>
            <span className="fs-value block truncate">{selectedLabel}</span>
            <span
              className={`fs-sub block truncate ${isUnresolved ? "text-[#b45309]" : ""}`}
              title={policySub ?? selectedSub ?? undefined}
            >
              {policySub ?? selectedSub}
            </span>
          </>
        )}
      </button>

      <div
        className="fs-dropdown fs-bookingfor-dd"
        onClick={(e) => e.stopPropagation()}
        role="presentation"
      >
        <div className="flex items-center gap-[8px] rounded-[10px] border border-[#e5e9ee] px-[10px] py-[8px]">
          <Search aria-hidden className="size-[15px] shrink-0 text-[#6b7785]" />
          <input
            ref={inputRef}
            type="text"
            role="combobox"
            aria-expanded={open}
            aria-controls={listboxId}
            aria-autocomplete="list"
            aria-activedescendant={activeRow ? optionId(activeRow.businessUserId) : undefined}
            aria-label="Search colleagues by name or email"
            placeholder="Search by name or email"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onKeyDown={onKeyDown}
            className="min-w-0 flex-1 border-0 bg-transparent text-[13px] text-[#1f2933] outline-none placeholder:text-[#9aa4b1]"
          />
        </div>

        <p className="mt-[8px] mb-[4px] px-[2px] text-[11px] leading-[15px] text-[#6b7785]">
          Pick who this trip is for. Their travel policy applies, and you stay the requester.
        </p>

        <ul id={listboxId} role="listbox" aria-label="Booking for" className="m-0 list-none p-0">
          {all.error ? (
            <li className="px-[10px] py-[12px] text-[12px] text-[#b45309]">
              {all.error.message}{" "}
              <button
                type="button"
                className="underline underline-offset-2"
                onClick={(e) => {
                  e.stopPropagation();
                  void all.refetch();
                }}
              >
                Try again
              </button>
            </li>
          ) : null}

          {all.isLoading ? (
            <li className="px-[10px] py-[12px] text-[12px] text-[#6b7785]">Loading colleagues…</li>
          ) : null}

          {!all.hasSession ? (
            <li className="px-[10px] py-[12px] text-[12px] text-[#6b7785]">
              Sign in to request travel for a colleague.
            </li>
          ) : null}

          {/* Self is pinned above the colleagues and outside the search results
              only when it matches — a list that still shows "Myself" while a
              search says "no matches" reads as a broken search. */}
          {rows
            .filter((t) => t.isSelf)
            .map((t) => (
              <Row
                key={t.businessUserId}
                id={optionId(t.businessUserId)}
                traveller={t}
                selected={value === null}
                active={activeRow?.businessUserId === t.businessUserId}
                onSelect={select}
                onHover={() => setActiveId(t.businessUserId)}
              />
            ))}

          {colleagues.length > 0 ? (
            <li
              role="presentation"
              className="mt-[6px] px-[10px] pt-[6px] pb-[2px] text-[10px] font-bold tracking-wide text-[#9aa4b1] uppercase"
            >
              Your colleagues
            </li>
          ) : null}

          {colleagues.map((t) => (
            <Row
              key={t.businessUserId}
              id={optionId(t.businessUserId)}
              traveller={t}
              selected={value === t.businessUserId}
              active={activeRow?.businessUserId === t.businessUserId}
              onSelect={select}
              onHover={() => setActiveId(t.businessUserId)}
            />
          ))}

          {all.hasSession && !all.isLoading && !all.error && rows.length === 0 ? (
            <li className="px-[10px] py-[12px] text-[12px] text-[#6b7785]">
              {isSearching ? "Searching…" : `No colleague matches “${search}”.`}
            </li>
          ) : null}

          {all.hasSession &&
          !all.isLoading &&
          !all.error &&
          search === "" &&
          colleagues.length === 0 &&
          selfRow ? (
            <li className="px-[10px] py-[10px] text-[11px] leading-[15px] text-[#6b7785]">
              You have no colleagues to book for in your policy group yet.
            </li>
          ) : null}
        </ul>
      </div>
    </>
  );
}
