"use client";

import { Fragment, useEffect, useRef, useState, type ReactNode } from "react";

import type {
  PolicyPropertyRef,
  PolicyScope,
  ResolvedSetting,
} from "@/services/travel-policy/travel-policy.client";
import { searchHotelsAndChains } from "@/services/travel-policy/travel-policy.client";
import {
  BOOKING_FLAGS,
  CABINS,
  DEFAULT_FILTERS,
  HOTEL_CHAIN_FILTER,
  SETTING_UNITS,
  SPECIFIC_PROPERTIES_FLAG,
  STAR_CHIPS,
  approvalLabel,
  cx,
  sanitizeNumeric,
  tilesFor,
  type ScopeDraft,
  type TileSpec,
} from "@/services/travel-policy/policy-format";

/**
 * The rule tiles on a group's tab — six settings on a flight tab (LEIS-976),
 * ten on a hotel tab (LEIS-993).
 *
 * Markup and classes are the design's own (`.bp-tile`, `.bz-switch`,
 * `.bz-chips`, `.bp-elig`, `.bp-stars`, `.bp-suggest`, `.bp-token`), so the
 * vendored `biz-policy.css` styles all of it without a line of new CSS.
 *
 * ── Tiles, not settings ──────────────────────────────────────────────────
 *
 * This renders TILES, each of which holds one or more settings. On the flight
 * tabs that is still one setting per tile and the output is unchanged. On the
 * hotel tabs three tiles hold two settings each — a star cap with its nightly
 * rate, the default filters with their preferred chains, the booking flags with
 * the hotels they name — because the admin makes one decision in each case even
 * though two values are stored.
 *
 * The tile layout lives in `policy-format.ts`; the server's registry order
 * still decides the SAVE DIFF and the Traveler view, and the two are kept in
 * step by hand rather than derived from each other, because they answer
 * different questions ("what does this page look like" vs "what did you
 * change").
 *
 * ── Errors ───────────────────────────────────────────────────────────────
 *
 * A tile shows the first error among its settings, and each sub-control gets
 * `is-invalid` independently. That is the design's own arrangement — it puts
 * `err: 'maxRate'` on the eligibility tile — and it matters for the one
 * cross-setting rule: "add at least one hotel or chain" is keyed on
 * `flaggedProperties`, which is the control the admin has to act on, not on the
 * chip they clicked.
 */

function Tile({
  icon,
  title,
  desc,
  wide,
  inline,
  error,
  children,
}: {
  icon: string;
  title: string;
  desc: string;
  wide?: boolean;
  inline?: boolean;
  error?: string;
  children: ReactNode;
}) {
  return (
    <div className={cx("bp-tile", wide && "is-wide", inline && "is-inline", error && "has-error")}>
      <div className="bp-tile-head">
        <span className="bp-tile-icon" aria-hidden="true">
          <i className={`bi ${icon}`} />
        </span>
        <div className="bp-min0">
          <h3 className="bp-tile-title">{title}</h3>
          <p className="bp-tile-desc">{desc}</p>
        </div>
      </div>
      <div className="bp-tile-ctrl">{children}</div>
      {error ? (
        <span className="bz-error" role="alert">
          {error}
        </span>
      ) : null}
    </div>
  );
}

/**
 * A number field that only accepts digits (and, for money, up to two decimals).
 *
 * The caret is restored after sanitising. Without that, typing into the middle
 * of "1000" moves the cursor to the end on every keystroke, which makes
 * correcting a figure effectively impossible — the design's own `onlyNumbers`
 * does the same thing for the same reason.
 *
 * Empty is a real, saveable value: PRD §8.5's "no limit". Hence the `No limit`
 * placeholder rather than a `0`.
 */
function NumberField({
  id,
  value,
  money,
  unit,
  label,
  invalid,
  onChange,
}: {
  id: string;
  value: string;
  money?: boolean;
  unit: string;
  label: string;
  invalid: boolean;
  onChange: (next: string) => void;
}) {
  const ref = useRef<HTMLInputElement>(null);

  const handle = (event: React.ChangeEvent<HTMLInputElement>) => {
    const el = event.target;
    const { value: next, caret } = sanitizeNumeric(
      el.value,
      el.selectionStart ?? el.value.length,
      Boolean(money)
    );
    onChange(next);
    if (next !== el.value) {
      // Applied after React's own value write, or React restores the old caret.
      requestAnimationFrame(() => {
        try {
          ref.current?.setSelectionRange(caret, caret);
        } catch {
          /* not focusable — nothing to restore */
        }
      });
    }
  };

  const input = (
    <input
      ref={ref}
      type="text"
      id={id}
      className={cx("bz-input", invalid && "is-invalid")}
      inputMode={money ? "decimal" : "numeric"}
      placeholder="No limit"
      value={value}
      aria-label={label}
      aria-invalid={invalid || undefined}
      autoComplete="off"
      onChange={handle}
    />
  );

  return (
    <div className={cx("bp-num", money && "is-money")}>
      {money ? (
        <div className="bz-affix">
          <span className="bz-affix-pre">$</span>
          {input}
        </div>
      ) : (
        input
      )}
      <span className="bp-unit">{unit}</span>
    </div>
  );
}

function SwitchField({
  checked,
  label,
  onText,
  offText,
  onChange,
}: {
  checked: boolean;
  label: string;
  onText: string;
  offText: string;
  onChange: (next: boolean) => void;
}) {
  return (
    <label className="bz-switch">
      <input
        type="checkbox"
        checked={checked}
        aria-label={label}
        onChange={(e) => onChange(e.target.checked)}
      />
      <span className="bz-switch-track" />
      <span className="bz-switch-text">{checked ? onText : offText}</span>
    </label>
  );
}

/**
 * A closed multi-select rendered as chips.
 *
 * The selection is kept in the VOCABULARY's order, not the order the chips were
 * clicked. The server stores it that way and decides what to write and what to
 * log by comparing JSON, so a re-ordered selection would otherwise read as a
 * change — the same reason the cabin chips do this.
 */
function ChipSet({
  list,
  selected,
  label,
  invalid,
  onToggle,
}: {
  list: ReadonlyArray<[string, string]>;
  selected: readonly string[];
  label: string;
  invalid?: boolean;
  onToggle: (next: string[]) => void;
}) {
  return (
    <div className={cx("bz-chips", invalid && "is-invalid")} role="group" aria-label={label}>
      {list.map(([key, text]) => {
        const on = selected.includes(key);
        return (
          <button
            type="button"
            key={key}
            className="bz-chip"
            aria-pressed={on}
            onClick={() =>
              onToggle(
                list.map(([k]) => k).filter((k) => (k === key ? !on : selected.includes(k)))
              )
            }
          >
            {text}
          </button>
        );
      })}
    </div>
  );
}

/**
 * The Maximum eligibility star row.
 *
 * Clicking the current cap clears it to "Any class" — the design's own
 * behaviour (`biz-policy.js:813`), and the only way to reach the blank state
 * from a chip row at all. Blank is stored as `isOn: false`, so the evaluator
 * skips the rule rather than comparing against a 0 cap that would flag every
 * property in existence.
 */
function StarChips({
  value,
  onChange,
}: {
  value: number;
  onChange: (next: number) => void;
}) {
  return (
    <div className="bp-stars-wrap">
      <span className="bp-elig-label">Up to</span>
      <div className="bp-stars" role="group" aria-label="Maximum hotel class">
        {STAR_CHIPS.map((star) => (
          <button
            type="button"
            key={star}
            className="bp-star"
            aria-pressed={value > 0 && star <= value}
            aria-label={`Up to ${star} star${star > 1 ? "s" : ""}`}
            onClick={() => onChange(value === star ? 0 : star)}
          >
            <i className="bi bi-star-fill" aria-hidden="true" />
          </button>
        ))}
      </div>
      <span className="bp-stars-text">{value > 0 ? `${value}-star` : "Any class"}</span>
    </div>
  );
}

/**
 * The hotel / chain typeahead, as tokens plus a search box.
 *
 * Entries are stored as `{ type, code, label }` and the evaluator matches on
 * `code`, so this only ever adds what the lookup returned — unlike the design
 * mock, which lets the admin add any typed string. A free-text entry would
 * produce a flag that silently never fires, because nothing downstream has a
 * name to match it against.
 *
 * `allowProperties` is false for the preferred-chains picker: a single property
 * cannot be "preferred" as a search filter, only a chain can.
 */
function RefPicker({
  id,
  token,
  selected,
  allowProperties,
  placeholder,
  invalid,
  onChange,
}: {
  id: string;
  token: string | null;
  selected: readonly PolicyPropertyRef[];
  allowProperties: boolean;
  placeholder: string;
  invalid?: boolean;
  onChange: (next: PolicyPropertyRef[]) => void;
}) {
  const [term, setTerm] = useState("");
  const [results, setResults] = useState<PolicyPropertyRef[]>([]);
  const [open, setOpen] = useState(false);

  // Debounced, and the in-flight result is discarded when the term has moved
  // on — without the `cancelled` latch a slow early request can land after a
  // fast later one and repopulate the list with stale matches.
  useEffect(() => {
    const q = term.trim();
    if (!token || q.length < 2) {
      setResults([]);
      setOpen(false);
      return;
    }
    let cancelled = false;
    const timer = setTimeout(async () => {
      const res = await searchHotelsAndChains(token, q);
      if (cancelled) return;
      const rows = (res.success ? res.data?.results : null) ?? [];
      setResults(
        rows.filter(
          (row) =>
            (allowProperties || row.type === "CHAIN") &&
            !selected.some((s) => s.type === row.type && s.code === row.code)
        )
      );
      setOpen(true);
    }, 250);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [term, token, allowProperties, selected]);

  const add = (ref: PolicyPropertyRef) => {
    onChange([...selected, ref]);
    setTerm("");
    setResults([]);
    setOpen(false);
  };

  return (
    <div className="bp-hotel-pick">
      <div className="bp-suggest-wrap">
        <div className="bz-affix is-icon">
          <i className="bi bi-search bz-affix-pre" aria-hidden="true" />
          <input
            type="text"
            id={id}
            className={cx("bz-input", invalid && "is-invalid")}
            placeholder={placeholder}
            autoComplete="off"
            role="combobox"
            aria-expanded={open}
            aria-controls={`${id}-suggest`}
            aria-label={placeholder}
            value={term}
            onChange={(e) => setTerm(e.target.value)}
          />
        </div>
        <div className="bp-suggest" id={`${id}-suggest`} role="listbox" hidden={!open}>
          {results.length === 0 ? (
            <button type="button" role="option" aria-selected={false} disabled>
              No matches
            </button>
          ) : (
            results.map((row) => (
              <button
                type="button"
                key={`${row.type}:${row.code}`}
                role="option"
                aria-selected={false}
                onClick={() => add(row)}
              >
                <i
                  className={`bi ${row.type === "CHAIN" ? "bi-collection" : "bi-building"}`}
                  aria-hidden="true"
                />
                {row.label}
                {row.type === "CHAIN" ? " (chain)" : ""}
              </button>
            ))
          )}
        </div>
      </div>
      <div className="bp-tokens">
        {selected.map((ref) => (
          <span className="bp-token" key={`${ref.type}:${ref.code}`}>
            <i
              className={`bi ${ref.type === "CHAIN" ? "bi-collection" : "bi-building"}`}
              aria-hidden="true"
            />
            {ref.label}
            <button
              type="button"
              aria-label={`Remove ${ref.label}`}
              onClick={() =>
                onChange(selected.filter((s) => !(s.type === ref.type && s.code === ref.code)))
              }
            >
              <i className="bi bi-x" aria-hidden="true" />
            </button>
          </span>
        ))}
      </div>
    </div>
  );
}

/* ── one setting's control ──────────────────────────────────────────────── */

function controlFor(args: {
  setting: ResolvedSetting;
  id: string;
  value: unknown;
  invalid: boolean;
  token: string | null;
  draft: ScopeDraft;
  onChange: (setting: string, value: unknown) => void;
}): ReactNode {
  const { setting, id, value, invalid, token, draft, onChange } = args;
  const key = setting.setting;

  switch (setting.kind) {
    case "limit":
    case "money":
      return (
        <NumberField
          id={id}
          value={String(value ?? "")}
          money={setting.kind === "money"}
          unit={SETTING_UNITS[key] ?? ""}
          label={setting.label}
          invalid={invalid}
          onChange={(next) => onChange(key, next)}
        />
      );

    case "toggle":
      return (
        <SwitchField
          checked={Boolean(value)}
          label={setting.label}
          // The design's own two pairs of switch copy.
          onText={key === "allowExtraBaggage" ? "Paid bags allowed" : "Allowed"}
          offText={key === "allowExtraBaggage" ? "Not allowed" : "Only for themselves"}
          onChange={(next) => onChange(key, next)}
        />
      );

    case "approvalMode": {
      // A switch, like the other gates (Bhupesh, 2026-10-12). The stored value
      // stays the server's enum rather than becoming a boolean: the switch is a
      // view of it, and a third mode later costs this one control instead of a
      // schema change.
      // Matches the backend's own default (business-policy.service.ts's
      // APPROVAL_MODE_DEFAULT) — direct booking is opt-in, so an unresolved
      // value reads as Approval required, not the reverse.
      const required = String(value ?? "APPROVAL_REQUIRED") === "APPROVAL_REQUIRED";
      return (
        <SwitchField
          checked={required}
          label={setting.label}
          onText={approvalLabel("APPROVAL_REQUIRED")}
          offText={approvalLabel("NO_APPROVAL_REQUIRED")}
          onChange={(next) => onChange(key, next ? "APPROVAL_REQUIRED" : "NO_APPROVAL_REQUIRED")}
        />
      );
    }

    case "cabins": {
      const selected = Array.isArray(value) ? (value as string[]) : [];
      return (
        <ChipSet
          list={CABINS}
          selected={selected}
          label="Cabin classes"
          invalid={invalid}
          onToggle={(next) => onChange(key, next)}
        />
      );
    }

    case "stars":
      return (
        <StarChips
          value={typeof value === "number" ? value : Number(value ?? 0) || 0}
          onChange={(next) => onChange(key, next)}
        />
      );

    case "filterChips": {
      const selected = Array.isArray(value) ? (value as string[]) : [];
      return (
        <ChipSet
          list={DEFAULT_FILTERS}
          selected={selected}
          label="Default search filters"
          invalid={invalid}
          onToggle={(next) => onChange(key, next)}
        />
      );
    }

    case "flagChips": {
      const selected = Array.isArray(value) ? (value as string[]) : [];
      return (
        <ChipSet
          list={BOOKING_FLAGS}
          selected={selected}
          label="Flag these bookings"
          invalid={invalid}
          onToggle={(next) => onChange(key, next)}
        />
      );
    }

    case "chainList":
    case "propertyList": {
      // Revealed only when its companion chip is selected. Deselecting the chip
      // HIDES this but does not clear the list: re-selecting should bring the
      // admin's hotels back, because a chip toggle is not a delete.
      const isFlagList = setting.kind === "propertyList";
      const companion = isFlagList
        ? (draft.restrictedBookingFlags as string[] | undefined)
        : (draft.defaultSearchFilters as string[] | undefined);
      const trigger = isFlagList ? SPECIFIC_PROPERTIES_FLAG : HOTEL_CHAIN_FILTER;
      if (!Array.isArray(companion) || !companion.includes(trigger)) return null;

      const selected = Array.isArray(value) ? (value as PolicyPropertyRef[]) : [];
      return (
        <RefPicker
          id={id}
          token={token}
          selected={selected}
          allowProperties={isFlagList}
          placeholder={
            isFlagList ? "Search hotels or chains to flag" : "Search chains to prefer"
          }
          invalid={invalid}
          onChange={(next) => onChange(key, next)}
        />
      );
    }

    default:
      return null;
  }
}

export default function RuleTiles({
  scope,
  settings,
  draft,
  errors,
  token,
  onChange,
}: {
  scope: PolicyScope;
  settings: readonly ResolvedSetting[];
  draft: ScopeDraft;
  /** Keyed `<scope>.<setting>`, from the local check and from the server alike. */
  errors: Record<string, string>;
  /** Business session token, for the hotel/chain lookup. Null when it has not
   *  loaded yet, which only disables suggestions — never the controls. */
  token: string | null;
  onChange: (setting: string, value: unknown) => void;
}) {
  const bySetting = new Map(settings.map((s) => [s.setting, s]));
  const isInternational = scope.startsWith("INTERNATIONAL");

  const renderTile = (tile: TileSpec) => {
    // Only the settings this tab actually serves. A tile whose settings are all
    // absent renders nothing, so a tab that loses a setting server-side does
    // not leave an empty box behind.
    const present = tile.settings
      .map((key) => bySetting.get(key))
      .filter((s): s is ResolvedSetting => Boolean(s));
    if (present.length === 0) return null;

    const firstError = tile.settings
      .map((key) => errors[`${scope}.${key}`])
      .find((message) => Boolean(message));

    const controls = present.map((setting) => {
      const id = `tp-${scope}-${setting.setting}`;
      const control = controlFor({
        setting,
        id,
        value: draft[setting.setting],
        invalid: Boolean(errors[`${scope}.${setting.setting}`]),
        token,
        draft,
        onChange,
      });
      // Wrapped only in a row layout, where `.bp-min0` is what stops a flex
      // child from refusing to shrink. A stacked tile needs no wrapper, and a
      // single-control tile renders exactly the markup it did before tiles
      // could hold more than one setting.
      return tile.layout === 'row' ? (
        <div key={setting.setting} className="bp-min0">
          {control}
        </div>
      ) : (
        <Fragment key={setting.setting}>{control}</Fragment>
      );
    });

    return (
      <Tile
        key={tile.id}
        icon={tile.icon}
        title={tile.title}
        desc={tile.desc(isInternational)}
        wide={tile.wide}
        inline={tile.inline}
        error={firstError}
      >
        {/* `.bp-elig` is the design's own wrapper for two controls SIDE BY
            SIDE — the star chips and their nightly rate. Every other tile
            stacks, so its controls are plain siblings and a 520px typeahead
            keeps its width. */}
        {tile.layout === 'row' ? <div className="bp-elig">{controls}</div> : controls}
      </Tile>
    );
  };

  return <div className="bp-tiles">{tilesFor(scope).map(renderTile)}</div>;
}
