"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";

import { toast } from "@/lib/toast";
import {
  createMeetingType,
  fetchOverview,
  removeMeetingType,
  renameMeetingType,
  type GroupCard,
  type PolicyOverview,
} from "@/services/travel-policy/travel-policy.client";
import {
  MSG,
  cx,
  flightShortText,
  hotelShortText,
  formatDate,
  groupLook,
  plural,
  relativeDay,
  RULE_LABELS,
  RULE_TO_SETTING,
  formatSettingValue,
} from "@/services/travel-policy/policy-format";

import ChangeLogDrawer from "./ChangeLogDrawer";
import GroupMenu, { type GroupMenuAction } from "./GroupMenu";
import ManageMembersDrawer from "./ManageMembersDrawer";
import {
  CreateGroupModal,
  DeleteGroupModal,
  DuplicateGroupModal,
  RenameGroupModal,
} from "./GroupModals";
import { useAdminSession } from "./useAdminSession";
import { BzStat } from "@/components/ui/BzStat";
import { ADMIN_HOME } from "@/constants/business-routes";

/**
 * The Travel Policy overview (LEIS-975 / PRD §8.5), at /admin/travel-policy.
 *
 * Four blocks, as the design lays them out: a hero, four stat tiles, the policy
 * group cards, and a lower row pairing the shared meeting-type options with
 * Recent changes.
 *
 * ── Why this page brings its own hero ────────────────────────────────────
 *
 * `components/admin/AdminHero.tsx` is the older `.fra-ui` generation, and
 * `PaymentMethodsPage` already set the precedent that a page built on the
 * newer `.bz-ui` system renders its own `.bz-hero` instead. AdminHero's `NAV`
 * entry for this page is still filled in, so the other three admin pages link
 * here — it was a deliberate stub waiting for exactly this design.
 *
 * ── Why not `.container` ─────────────────────────────────────────────────
 *
 * The design's policy.php wraps everything in Bootstrap's `.container`, but
 * corp never loads full Bootstrap on /admin — only a trimmed modal-positioning
 * subset — so that class is inert here and the page ran edge to edge. Same
 * wrapper `PaymentMethodsPage` uses, and `max-w-[1320px]` is Bootstrap's own
 * xxl container width, so it lines up with the rest of the admin area.
 *
 * ── Admin gate ───────────────────────────────────────────────────────────
 *
 * `useAdminSession` handles it: no session → `/employee-login`; a session that
 * is not an ADMIN → `/srp/flights`. The API enforces it too (every route is
 * `requireBusinessAdmin`); the gate only avoids rendering a page that would
 * answer 403 to everything on it.
 */
export default function TravelPolicyPage() {
  const router = useRouter();
  const { token } = useAdminSession();

  const [overview, setOverview] = useState<PolicyOverview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [query, setQuery] = useState("");

  // One open-dialog slot per kind, rather than a single union: the ⋯ menu can
  // hand off to any of them and two are never open at once.
  const [creating, setCreating] = useState(false);
  const [renaming, setRenaming] = useState<GroupCard | null>(null);
  const [duplicating, setDuplicating] = useState<GroupCard | null>(null);
  const [deleting, setDeleting] = useState<GroupCard | null>(null);
  const [managing, setManaging] = useState<GroupCard | null>(null);
  const [logOpen, setLogOpen] = useState(false);
  const [menu, setMenu] = useState<{ anchor: HTMLElement; group: GroupCard } | null>(null);

  // Every `setState` below follows the `await`. Clearing the error up front
  // would be a synchronous setState reached from the effect body — and it also
  // made a failed load flash its own message away the instant Try again was
  // pressed, before the retry had said anything.
  // The async work sits in a nested function, not directly in `load`'s body.
  // `react-hooks/set-state-in-effect` traces through an async function called
  // from an effect and counts its `setState`s as synchronous — the `await` is
  // not a boundary it reasons about. A nested callback IS one, which is the
  // shape the rule sanctions ("calling setState in a callback function"), and
  // it is the same shape the members drawer's first load already uses.
  const load = useCallback(() => {
    void (async () => {
      if (!token) return;
      const res = await fetchOverview(token);
      setLoading(false);
      if (!res.success || !res.data) {
        setError(res.message ?? "We could not load your travel policy. Please try again.");
        return;
      }
      setError(null);
      setOverview(res.data);
    })();
  }, [token]);

  useEffect(() => {
    if (!token) return;
    void load();
  }, [token, load]);

  if (!token) return null;

  const groups = overview?.groups ?? [];
  const term = query.trim().toLowerCase();
  const visible = term
    ? groups.filter(
        (g) =>
          g.name.toLowerCase().includes(term) || (g.description ?? "").toLowerCase().includes(term)
      )
    : groups;

  const onMenuSelect = (group: GroupCard, action: GroupMenuAction) => {
    if (action === "edit") router.push(`/admin/travel-policy/${group.id}`);
    if (action === "members") setManaging(group);
    if (action === "rename") setRenaming(group);
    if (action === "duplicate") setDuplicating(group);
    if (action === "delete") setDeleting(group);
  };

  return (
    <section className="bz-ui bz-page bp-page">
      <div className={"mx-auto w-full max-w-[1320px] px-3"}>
        <section className="bz-hero">
          <div className="bz-hero-text">
            <ol className="bz-crumbs">
              <li>
                <Link href={ADMIN_HOME}>Admin</Link>
              </li>
              <li>
                <Link href="/admin/flight-approvals">Corporate Travel</Link>
              </li>
              <li aria-current="page">Travel policy</li>
            </ol>
            <h1 className="bz-hero-title">Travel Policy</h1>
            <p className="bz-hero-sub">
              Set flight and hotel rules for each group. Nothing is blocked — requests outside the
              rules can still be submitted and are flagged for your review.
            </p>
          </div>
          <div className="bz-hero-actions">
            <button
              type="button"
              className="bz-btn bz-btn-lg bz-btn-glass"
              onClick={() => setLogOpen(true)}
            >
              <i className="bi bi-clock-history" aria-hidden="true" />
              <span>Change log</span>
            </button>
            <button
              type="button"
              className="bz-btn bz-btn-lg bz-btn-primary"
              onClick={() => setCreating(true)}
            >
              <i className="bi bi-plus-lg" aria-hidden="true" />
              <span>Create group</span>
            </button>
          </div>
        </section>

        {loading && (
          <p className="bp-sub" role="status">
            Loading your travel policy…
          </p>
        )}

        {!loading && error && (
          <div className="bp-empty">
            <i className="bi bi-exclamation-circle" aria-hidden="true" />
            <strong>{error}</strong>
            <button type="button" className="bz-link" onClick={() => void load()}>
              Try again
            </button>
          </div>
        )}

        {!loading && !error && overview && (
          <>
            <div className="bz-stats">
              <BzStat
                tone="navy"
                icon="bi-collection"
                label="Policy groups"
                value={String(overview.stats.groupCount)}
                sub={`1 default · ${plural(Math.max(0, overview.stats.groupCount - 1), "custom group")}`}
              />
              <BzStat
                tone="green"
                icon="bi-people"
                label="Employees covered"
                value={String(overview.stats.employeesCovered)}
                sub={`${overview.stats.onDefaultPolicy} on the default policy`}
              />
              <BzStat
                tone="indigo"
                icon="bi-pencil-square"
                label="Policy changes"
                value={String(overview.stats.recentChanges)}
                sub={`In the last ${overview.stats.recentWindowDays} days`}
              />
              <BzStat
                tone="amber"
                icon="bi-tags"
                label="Meeting types"
                value={String(overview.stats.activeMeetingTypes)}
                sub="Shared by all groups"
              />
            </div>

            <section className="bp-block" aria-labelledby="tpGroupsTitle">
              <div className="bp-block-head">
                <div>
                  <h2 className="bp-h2" id="tpGroupsTitle">
                    Policy groups
                  </h2>
                  <p className="bp-sub">Each employee follows the rules of one group.</p>
                </div>
                <div className="bz-affix is-icon bp-search">
                  <i className="bi bi-search bz-affix-pre" aria-hidden="true" />
                  <label className="bz-sr" htmlFor="tpSearch">
                    Search groups
                  </label>
                  <input
                    type="search"
                    className="bz-input"
                    id="tpSearch"
                    placeholder="Search groups"
                    autoComplete="off"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                  />
                </div>
              </div>

              <div className="bp-ggrid">
                {visible.map((group) => (
                  <GroupCardView
                    key={group.id}
                    group={group}
                    onMenu={(anchor) => setMenu({ anchor, group })}
                  />
                ))}

                {term && visible.length === 0 && (
                  <div className="bp-empty">
                    <i className="bi bi-search" aria-hidden="true" />
                    <strong>No groups match &ldquo;{query.trim()}&rdquo;</strong>
                    <span>Try another name, or create a new group.</span>
                  </div>
                )}

                {!term && (
                  <button type="button" className="bp-gcard-new" onClick={() => setCreating(true)}>
                    <span className="bz-icon-tile" aria-hidden="true">
                      <i className="bi bi-plus-lg" />
                    </span>
                    <strong>Create a group</strong>
                    <small>Start from an existing group&rsquo;s rules</small>
                  </button>
                )}
              </div>
            </section>

            <div className="bp-lower">
              <MeetingTypesCard token={token} overview={overview} onChanged={() => void load()} />
              <RecentChangesCard overview={overview} onViewAll={() => setLogOpen(true)} />
            </div>
          </>
        )}
      </div>

      {menu && (
        <GroupMenu
          anchor={menu.anchor}
          group={menu.group}
          context="card"
          onSelect={(action) => onMenuSelect(menu.group, action)}
          onClose={() => setMenu(null)}
        />
      )}

      {creating && (
        <CreateGroupModal
          token={token}
          groups={groups}
          onClose={() => setCreating(false)}
          onCreated={(group) => {
            setCreating(false);
            // Straight into the new group's rules, as the design does — the
            // admin created it in order to set them.
            router.push(`/admin/travel-policy/${group.id}`);
          }}
        />
      )}
      {renaming && (
        <RenameGroupModal
          token={token}
          group={renaming}
          groups={groups}
          onClose={() => setRenaming(null)}
          onRenamed={() => {
            setRenaming(null);
            void load();
          }}
        />
      )}
      {duplicating && (
        <DuplicateGroupModal
          token={token}
          group={duplicating}
          groups={groups}
          onClose={() => setDuplicating(null)}
          onDuplicated={() => {
            setDuplicating(null);
            void load();
          }}
        />
      )}
      {deleting && (
        <DeleteGroupModal
          token={token}
          group={deleting}
          groups={groups}
          onClose={() => setDeleting(null)}
          onDeleted={() => {
            setDeleting(null);
            void load();
          }}
        />
      )}
      {managing && (
        <ManageMembersDrawer
          token={token}
          group={managing}
          onClose={() => setManaging(null)}
          onSaved={() => {
            setManaging(null);
            void load();
          }}
        />
      )}
      {logOpen && (
        <ChangeLogDrawer token={token} groups={groups} onClose={() => setLogOpen(false)} />
      )}
    </section>
  );
}

/* ── pieces ────────────────────────────────────────────────────────────────── */

function GroupCardView({
  group,
  onMenu,
}: {
  group: GroupCard;
  onMenu: (anchor: HTMLElement) => void;
}) {
  const look = groupLook(group);
  return (
    <article className={cx("bz-card", "bp-gcard", group.isDefault && "is-default")}>
      <div className="bp-gcard-top">
        <span className={`bz-icon-tile tone-${look.tone}`} aria-hidden="true">
          <i className={`bi ${look.icon}`} />
        </span>
        <div className="bp-gcard-name">
          <h3>
            <Link href={`/admin/travel-policy/${group.id}`}>{group.name}</Link>
            {group.isDefault && <span className="bz-badge">Default</span>}
          </h3>
          <p>{group.description || "No description"}</p>
        </div>
        <button
          type="button"
          className="bz-icon-btn"
          aria-haspopup="menu"
          aria-label={`More actions for ${group.name}`}
          onClick={(e) => onMenu(e.currentTarget)}
        >
          <i className="bi bi-three-dots" aria-hidden="true" />
        </button>
      </div>

      <dl className="bp-gcard-rules">
        <div>
          <dt>
            <i className="bi bi-airplane" aria-hidden="true" />
            Domestic flights
          </dt>
          <dd>{flightShortText(group.flights.DOMESTIC_FLIGHT)}</dd>
        </div>
        <div>
          <dt>
            <i className="bi bi-globe-americas" aria-hidden="true" />
            International flights
          </dt>
          <dd>{flightShortText(group.flights.INTERNATIONAL_FLIGHT)}</dd>
        </div>
        {/* The hotel tabs joined the card in LEIS-993. They are summarised with
            their own formatter, not the flight one: a hotel tab has a star
            class and a nightly cap where a flight tab has cabins and a trip
            fare, and "Economy · no fare cap" on a hotel row would be nonsense
            rather than merely unset. */}
        <div>
          <dt>
            <i className="bi bi-building" aria-hidden="true" />
            Domestic hotels
          </dt>
          <dd>{hotelShortText(group.hotels.DOMESTIC_HOTEL)}</dd>
        </div>
        <div>
          <dt>
            <i className="bi bi-buildings" aria-hidden="true" />
            International hotels
          </dt>
          <dd>{hotelShortText(group.hotels.INTERNATIONAL_HOTEL)}</dd>
        </div>
      </dl>

      <div className="bp-gcard-foot">
        <div className="bp-gcard-people">
          <span>
            <strong>{group.memberCount}</strong> {group.memberCount === 1 ? "member" : "members"}
          </span>
        </div>
        <Link
          className="bz-btn bz-btn-sm bz-btn-secondary"
          href={`/admin/travel-policy/${group.id}`}
        >
          Edit policy
          <i className="bi bi-arrow-right" aria-hidden="true" />
        </Link>
      </div>

      <p className="bp-gcard-updated">
        <i className="bi bi-clock" aria-hidden="true" />
        Updated {formatDate(group.updatedAt)}
        {group.updatedBy ? ` by ${group.updatedBy}` : ""}
      </p>
    </article>
  );
}

/**
 * The shared Meeting type options (PRD §8.5: "managed on this page").
 *
 * Inline add, rename and remove rather than a modal apiece — the design does it
 * this way and it is right: these are one-word strings, and a dialog per edit
 * would be more ceremony than the content deserves. Rename happens in place on
 * the row.
 */
function MeetingTypesCard({
  token,
  overview,
  onChanged,
}: {
  token: string;
  overview: PolicyOverview;
  onChanged: () => void;
}) {
  const active = overview.meetingTypes.filter((m) => m.isActive);
  const [draft, setDraft] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editDraft, setEditDraft] = useState("");
  const [editError, setEditError] = useState("");

  const validate = (value: string, exceptId?: string): string => {
    const label = value.trim();
    if (!label) return MSG.mtEmpty;
    if (label.length > 40) return MSG.mtLong;
    if (
      active.some((m) => m.id !== exceptId && m.label.trim().toLowerCase() === label.toLowerCase())
    ) {
      return MSG.mtTaken;
    }
    return "";
  };

  const add = async () => {
    const message = validate(draft);
    if (message) {
      setError(message);
      return;
    }
    setBusy(true);
    const res = await createMeetingType(token, draft.trim());
    setBusy(false);
    if (!res.success) {
      setError(res.message ?? "We could not add that meeting type.");
      return;
    }
    setDraft("");
    setError("");
    toast.success(res.message ?? "Meeting type added.");
    onChanged();
  };

  const saveRename = async (id: string) => {
    const message = validate(editDraft, id);
    if (message) {
      setEditError(message);
      return;
    }
    setBusy(true);
    const res = await renameMeetingType(token, id, editDraft.trim());
    setBusy(false);
    if (!res.success) {
      setEditError(res.message ?? "We could not rename that meeting type.");
      return;
    }
    setEditingId(null);
    setEditError("");
    toast.success(res.message ?? "Meeting type renamed.");
    onChanged();
  };

  const remove = async (id: string, label: string) => {
    setBusy(true);
    const res = await removeMeetingType(token, id);
    setBusy(false);
    if (!res.success) {
      toast.error(res.message ?? "We could not remove that meeting type.");
      return;
    }
    toast.success(res.message ?? `“${label}” removed.`);
    onChanged();
  };

  return (
    <section className="bz-card" aria-labelledby="tpMtTitle">
      <div className="bz-card-head">
        <div>
          <h2 className="bz-card-title" id="tpMtTitle">
            Meeting types
          </h2>
          <p className="bz-card-sub">
            Travelers pick one when they request travel. Applies to every group.
          </p>
        </div>
      </div>
      <div className="bz-card-body">
        <ul className="bp-mt-list">
          {active.length === 0 && (
            <li className="bp-mt-empty">
              No meeting types yet. Travelers won&rsquo;t see the Meeting type field until you add
              one.
            </li>
          )}
          {active.map((option) =>
            editingId === option.id ? (
              <li className="bp-mt" key={option.id}>
                <i className="bi bi-tag" aria-hidden="true" />
                <input
                  type="text"
                  className={cx("bz-input", editError && "is-invalid")}
                  value={editDraft}
                  maxLength={60}
                  aria-label={`Rename ${option.label}`}
                  onChange={(e) => {
                    setEditDraft(e.target.value);
                    setEditError("");
                  }}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      void saveRename(option.id);
                    }
                    if (e.key === "Escape") {
                      e.preventDefault();
                      setEditingId(null);
                      setEditError("");
                    }
                  }}
                  autoFocus
                />
                <button
                  type="button"
                  className="bz-icon-btn"
                  onClick={() => void saveRename(option.id)}
                  disabled={busy}
                  aria-label="Save"
                  title="Save"
                >
                  <i className="bi bi-check2" />
                </button>
                <button
                  type="button"
                  className="bz-icon-btn"
                  onClick={() => {
                    setEditingId(null);
                    setEditError("");
                  }}
                  aria-label="Cancel"
                  title="Cancel"
                >
                  <i className="bi bi-x-lg" />
                </button>
              </li>
            ) : (
              <li className="bp-mt" key={option.id}>
                <i className="bi bi-tag" aria-hidden="true" />
                <span>{option.label}</span>
                <button
                  type="button"
                  className="bz-icon-btn"
                  onClick={() => {
                    setEditingId(option.id);
                    setEditDraft(option.label);
                    setEditError("");
                  }}
                  aria-label={`Rename ${option.label}`}
                  title="Rename"
                >
                  <i className="bi bi-pencil" />
                </button>
                <button
                  type="button"
                  className="bz-icon-btn is-danger"
                  onClick={() => void remove(option.id, option.label)}
                  disabled={busy}
                  aria-label={`Remove ${option.label}`}
                  title="Remove"
                >
                  <i className="bi bi-x-lg" />
                </button>
              </li>
            )
          )}
        </ul>

        {editError && (
          <span className="bz-error" role="alert">
            {editError}
          </span>
        )}

        <form
          className="bp-mt-add"
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            void add();
          }}
        >
          <label className="bz-sr" htmlFor="tpMtNew">
            New meeting type
          </label>
          <input
            type="text"
            className={cx("bz-input", error && "is-invalid")}
            id="tpMtNew"
            maxLength={60}
            placeholder="Add a meeting type, e.g. Site visit"
            autoComplete="off"
            value={draft}
            onChange={(e) => {
              setDraft(e.target.value);
              setError("");
            }}
          />
          <button type="submit" className="bz-btn bz-btn-navy" disabled={busy}>
            <i className="bi bi-plus-lg" aria-hidden="true" />
            <span>Add</span>
          </button>
        </form>
        <span className="bz-error" role="alert">
          {error}
        </span>
      </div>
    </section>
  );
}

function RecentChangesCard({
  overview,
  onViewAll,
}: {
  overview: PolicyOverview;
  onViewAll: () => void;
}) {
  return (
    <section className="bz-card" aria-labelledby="tpRecentTitle">
      <div className="bz-card-head">
        <div>
          <h2 className="bz-card-title" id="tpRecentTitle">
            Recent changes
          </h2>
          <p className="bz-card-sub">Latest edits across all groups.</p>
        </div>
        <button type="button" className="bz-link" onClick={onViewAll}>
          View all
          <i className="bi bi-arrow-right" aria-hidden="true" />
        </button>
      </div>
      <ul className="bp-recent">
        {overview.recent.length === 0 && <li className="bp-mt-empty">No changes yet.</li>}
        {overview.recent.map((row) => {
          // A RULE row's setting and change are derived from the same formatter
          // the controls use; every other kind carries its own prose.
          const setting =
            row.kind === "RULE" && row.rule
              ? (RULE_LABELS[row.rule] ?? row.rule)
              : (row.setting ?? "—");
          const change =
            row.kind === "RULE" && row.rule
              ? `${formatSettingValue(
                  RULE_TO_SETTING[row.rule] ?? row.rule,
                  row.previousValue,
                  row.previousIsOn ?? row.previousValue !== null
                )} → ${formatSettingValue(
                  RULE_TO_SETTING[row.rule] ?? row.rule,
                  row.newValue,
                  row.newIsOn ?? row.newValue !== null
                )}`
              : (row.summary ?? "");
          return (
            <li key={row.id}>
              <span className="bp-recent-dot" aria-hidden="true" />
              <div className="bp-recent-text">
                <p>
                  <strong>{setting}</strong> <span className="bp-chg">{change}</span>
                </p>
                <small>
                  {row.group.name}
                  {row.scopeLabel ? ` · ${row.scopeLabel}` : ""} · {relativeDay(row.at)}
                </small>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}
