"use client";

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

import { toast } from "@/lib/toast";
import {
  fetchOverview,
  fetchRules,
  saveRules,
  type GroupCard,
  type GroupRules,
  type PolicyScope,
} from "@/services/travel-policy/travel-policy.client";
import {
  EDITABLE_SCOPES,
  SCOPE_GROUPS,
  SCOPE_META,
  travellerRowsFor,
  cx,
  diffDraft,
  errorsForScope,
  formatDate,
  groupLook,
  isDirty as draftIsDirty,
  kindsOf,
  plural,
  sameDraft,
  toDraft,
  toTabEdit,
  validateDraft,
  type PolicyDraft,
} from "@/services/travel-policy/policy-format";

import ChangeLogDrawer from "./ChangeLogDrawer";
import GroupMenu, { type GroupMenuAction } from "./GroupMenu";
import ManageMembersDrawer from "./ManageMembersDrawer";
import RuleTiles from "./RuleTiles";
import {
  DiscardChangesModal,
  LeaveGuardModal,
  SaveChangesModal,
  TravelerSummaryDrawer,
} from "./EditorDialogs";
import { DeleteGroupModal, DuplicateGroupModal, RenameGroupModal } from "./GroupModals";
import { useAdminSession } from "./useAdminSession";
import { ADMIN_HOME } from "@/constants/business-routes";

/**
 * One group's policy rules (LEIS-975 / PRD §8.5's group policy page).
 *
 * Three columns, as the design lays them out: a section nav for the four tabs,
 * the rule tiles for the selected one, and a live "Traveler view" panel showing
 * what a member of this group would actually see. A sticky dock appears as soon
 * as anything is dirty.
 *
 * ── 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.
 *
 * ── The draft ────────────────────────────────────────────────────────────
 *
 * `saved` and `draft` are both full `PolicyDraft`s — every editable tab, not
 * just the open one — because the dock saves everything dirty at once and the
 * per-tab badges have to say which tabs those are. Switching tabs is therefore
 * free and loses nothing, which is the behaviour the design's section nav
 * implies by marking a tab "Unsaved" while you are looking at another.
 *
 * ── The navigation guard ─────────────────────────────────────────────────
 *
 * Three exits have to be covered and they need different mechanisms:
 *
 *   1. **A reload or a closed tab** — `beforeunload`. Only the browser's own
 *      generic prompt is possible here; no page can word it.
 *   2. **An in-app link** — a capture-phase click listener on `a[href]`, which
 *      is what the design does. Next's `<Link>` renders a real anchor, so
 *      `preventDefault` stops the navigation and the intended href is held for
 *      the dialog to resume. The App Router has no official route-change guard,
 *      and this is both the smallest mechanism that works and the one the
 *      design already proved.
 *   3. **This page's own buttons** — handled directly, since they are ours.
 *
 * The Back button is deliberately NOT guarded: intercepting history requires
 * pushing a sentinel entry and racing `popstate`, which breaks the Back button
 * in ways users notice far more often than they lose a policy edit.
 */
export default function GroupPolicyEditor({ groupId }: { groupId: string }) {
  const router = useRouter();
  const { token } = useAdminSession();

  const [rules, setRules] = useState<GroupRules | null>(null);
  const [groups, setGroups] = useState<GroupCard[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);

  const [scope, setScope] = useState<PolicyScope>("DOMESTIC_FLIGHT");
  const [saved, setSaved] = useState<PolicyDraft>({});
  const [draft, setDraft] = useState<PolicyDraft>({});
  /** Server-side field errors, merged over the local ones until the next edit. */
  const [serverErrors, setServerErrors] = useState<Record<string, string>>({});

  const [confirming, setConfirming] = useState(false);
  const [discarding, setDiscarding] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [summaryOpen, setSummaryOpen] = useState(false);
  const [logOpen, setLogOpen] = useState(false);
  const [managing, setManaging] = useState(false);
  const [renaming, setRenaming] = useState(false);
  const [duplicating, setDuplicating] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [menu, setMenu] = useState<HTMLElement | null>(null);
  /** The href a guarded link click was heading for. */
  const [pendingHref, setPendingHref] = useState<string | null>(null);

  /* ── load ──────────────────────────────────────────────────────────────── */
  //
  // Every `setState` follows the `await`, so nothing here is a synchronous
  // setState reached from the effect body below.
  // 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;
      // The group list comes along for the modals: Duplicate needs the existing
      // names to suggest "(copy 2)", and Delete needs somewhere to move members.
      const [rulesRes, overviewRes] = await Promise.all([
        fetchRules(token, groupId),
        fetchOverview(token),
      ]);
      setLoading(false);

      if (!rulesRes.success || !rulesRes.data) {
        setLoadError(
          rulesRes.status === 404
            ? "That policy group no longer exists."
            : (rulesRes.message ?? "We could not load this group’s rules. Please try again.")
        );
        return;
      }

      setLoadError(null);
      setRules(rulesRes.data);
      const next = toDraft(rulesRes.data.tabs);
      setSaved(next);
      setDraft(next);
      setServerErrors({});
      if (overviewRes.success && overviewRes.data) setGroups(overviewRes.data.groups);
    })();
  }, [token, groupId]);

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

  /* ── derived ───────────────────────────────────────────────────────────── */
  const kinds = useMemo(() => (rules ? kindsOf(rules.tabs) : new Map()), [rules]);
  const localErrors = useMemo(() => validateDraft(draft, kinds), [draft, kinds]);
  const errors = useMemo(() => ({ ...serverErrors, ...localErrors }), [serverErrors, localErrors]);
  const dirty = draftIsDirty(saved, draft);
  const diffs = useMemo(
    () => (rules ? diffDraft(saved, draft, rules.tabs) : []),
    [rules, saved, draft]
  );
  const errorCount = Object.keys(errors).length;

  const card = groups.find((g) => g.id === groupId);
  const memberCount = card?.memberCount ?? 0;

  /* ── guards ────────────────────────────────────────────────────────────── */

  // A ref, not the state value: the listeners below are registered once and a
  // stale closure would read `dirty` as it was when they were attached.
  //
  // Written from an effect, not during render — a render-phase ref write is
  // exactly what `react-hooks/refs` catches, and under a concurrent render that
  // is thrown away it would leave the ref describing a draft that never
  // committed.
  const dirtyRef = useRef(dirty);
  useEffect(() => {
    dirtyRef.current = dirty;
  }, [dirty]);

  // The dock is `position: fixed`, and the stylesheet reserves room for it with
  // `body.bz-has-dock .bz-page { padding-bottom: 130px }` — on BODY, not on the
  // page element. Setting the class on the section instead was inert, and the
  // dock sat on top of the last rule tile.
  //
  // Removed on unmount as well as when the draft goes clean: navigating away
  // mid-edit would otherwise leave every other page padded for a dock that is
  // no longer there.
  useEffect(() => {
    document.body.classList.toggle("bz-has-dock", dirty);
    return () => document.body.classList.remove("bz-has-dock");
  }, [dirty]);

  useEffect(() => {
    const onBeforeUnload = (event: BeforeUnloadEvent) => {
      if (!dirtyRef.current) return;
      event.preventDefault();
      // Assigning returnValue is what actually triggers the prompt in the
      // browsers that still honour it; preventDefault alone is not enough
      // everywhere.
      event.returnValue = "";
    };
    window.addEventListener("beforeunload", onBeforeUnload);
    return () => window.removeEventListener("beforeunload", onBeforeUnload);
  }, []);

  useEffect(() => {
    const onClick = (event: MouseEvent) => {
      if (!dirtyRef.current) return;
      const anchor = (event.target as HTMLElement | null)?.closest(
        "a[href]"
      ) as HTMLAnchorElement | null;
      if (!anchor) return;

      const href = anchor.getAttribute("href");
      // Left out on purpose: in-page fragments (they navigate nowhere), new
      // tabs, and modified clicks — a cmd-click opens a second tab and leaves
      // this one, and its edits, exactly where they are.
      if (
        !href ||
        href.startsWith("#") ||
        anchor.target === "_blank" ||
        event.metaKey ||
        event.ctrlKey ||
        event.shiftKey ||
        event.button !== 0
      ) {
        return;
      }

      event.preventDefault();
      setPendingHref(anchor.href);
    };

    // Capture phase, so this runs before Next's own router click handler.
    document.addEventListener("click", onClick, true);
    return () => document.removeEventListener("click", onClick, true);
  }, []);

  /* ── editing ───────────────────────────────────────────────────────────── */
  const update = (setting: string, value: unknown) => {
    setDraft((current) => ({
      ...current,
      [scope]: { ...(current[scope] ?? {}), [setting]: value },
    }));
    // A server error is about the value that was sent, so it stops applying the
    // moment the value changes.
    setServerErrors((current) => {
      const key = `${scope}.${setting}`;
      if (!(key in current)) return current;
      const next = { ...current };
      delete next[key];
      return next;
    });
  };

  const resetScope = () => {
    setDraft((current) => ({ ...current, [scope]: { ...(saved[scope] ?? {}) } }));
  };

  const commit = async () => {
    if (!token || !rules || errorCount > 0 || submitting) return;
    setSubmitting(true);

    // Only the dirty tabs. Sending a clean one would be harmless (the server
    // diffs too) but would put it in the request for no reason.
    const tabs = EDITABLE_SCOPES.filter((s) => !sameDraft(saved[s], draft[s])).map((s) =>
      toTabEdit(s, draft[s] ?? {}, kinds)
    );

    const res = await saveRules(token, groupId, tabs);
    setSubmitting(false);

    if (!res.success) {
      setConfirming(false);
      if (res.errors) {
        // Straight onto the fields, in the same `<scope>.<setting>` shape the
        // local check uses.
        setServerErrors(res.errors);
        toast.error("Some rules could not be saved. Check the highlighted fields.");
        return;
      }
      toast.error(res.message ?? "We could not save this policy. Please try again.");
      return;
    }

    // Re-seeded from the server's own resolved view rather than from the draft:
    // it has canonicalised cabin order and collapsed blanks to `isOn: false`,
    // and trusting the draft would leave the page one save behind on both.
    if (res.data?.tabs) {
      setRules({ ...rules, tabs: res.data.tabs });
      const next = toDraft(res.data.tabs);
      setSaved(next);
      setDraft(next);
    } else {
      setSaved(draft);
    }
    setServerErrors({});
    setConfirming(false);
    toast.success(res.message ?? `Policy saved for ${rules.group.name}.`);
    // Member counts and "last edited" both moved.
    const overview = await fetchOverview(token);
    if (overview.success && overview.data) setGroups(overview.data.groups);
  };

  if (!token) return null;

  if (loading) {
    return (
      <section className="bz-ui bz-page bp-page">
        <div className={"mx-auto w-full max-w-[1320px] px-3"}>
          <p className="bp-sub" role="status">
            Loading this group&rsquo;s rules…
          </p>
        </div>
      </section>
    );
  }

  if (loadError || !rules) {
    return (
      <section className="bz-ui bz-page bp-page">
        <div className={"mx-auto w-full max-w-[1320px] px-3"}>
          <div className="bp-empty">
            <i className="bi bi-exclamation-circle" aria-hidden="true" />
            <strong>{loadError ?? "We could not load this group’s rules."}</strong>
            <Link className="bz-link" href="/admin/travel-policy">
              Back to Travel policy
            </Link>
          </div>
        </div>
      </section>
    );
  }

  const group = rules.group;
  const look = groupLook(group);
  const tab = rules.tabs.find((t) => t.scope === scope);
  const scopeDraft = draft[scope] ?? {};
  const scopeSaved = saved[scope] ?? {};

  const onMenuSelect = (action: GroupMenuAction) => {
    if (action === "rename") setRenaming(true);
    if (action === "duplicate") setDuplicating(true);
    if (action === "delete") setDeleting(true);
  };

  /** Navigate away, bypassing the guard — used once the dialog has consented. */
  const leaveTo = (href: string) => {
    setSaved(draft);
    dirtyRef.current = false;
    window.location.href = href;
  };

  return (
    <section className={cx("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/travel-policy">Travel policy</Link>
              </li>
              <li aria-current="page">{group.name}</li>
            </ol>
            <div className="bp-ghero-row">
              <span className={`bz-icon-tile bp-ghero-icon tone-${look.tone}`} aria-hidden="true">
                <i className={`bi ${look.icon}`} />
              </span>
              <div className="bp-min0">
                <h1 className="bz-hero-title">
                  {group.name}
                  {group.isDefault && <span className="bz-badge">Default</span>}
                </h1>
                {group.description && <p className="bz-hero-sub">{group.description}</p>}
              </div>
            </div>
            <div className="bz-hero-pills">
              <span className="bz-hero-pill">
                <i className="bi bi-people" aria-hidden="true" />
                {plural(memberCount, "member")}
              </span>
              {card && (
                <span className="bz-hero-pill">
                  <i className="bi bi-clock" aria-hidden="true" />
                  Updated {formatDate(card.updatedAt)}
                  {card.updatedBy ? ` by ${card.updatedBy}` : ""}
                </span>
              )}
            </div>
          </div>
          <div className="bz-hero-actions">
            {/* The default group's membership is "everyone not in another
                group" — not a list, so there is nothing to manage. */}
            {!group.isDefault && (
              <button
                type="button"
                className="bz-btn bz-btn-lg bz-btn-glass"
                onClick={() => setManaging(true)}
              >
                <i className="bi bi-person-gear" aria-hidden="true" />
                <span>Manage members</span>
              </button>
            )}
            <button
              type="button"
              className="bz-btn bz-btn-lg bz-btn-glass"
              onClick={() => setSummaryOpen(true)}
            >
              <i className="bi bi-eye" aria-hidden="true" />
              <span>Traveler summary</span>
            </button>
            <button
              type="button"
              className="bz-btn bz-btn-lg bz-btn-glass bp-hero-more"
              aria-haspopup="menu"
              aria-label="More actions"
              onClick={(e) => setMenu(e.currentTarget)}
            >
              <i className="bi bi-three-dots" aria-hidden="true" />
            </button>
          </div>
        </section>

        <div className="bp-editor">
          <nav className="bz-card bp-secnav" aria-label="Rule sections">
            {SCOPE_GROUPS.map((section) => (
              <div key={section.title}>
                <p className="bp-secnav-title">
                  <i className={`bi ${section.icon}`} aria-hidden="true" />
                  {section.title}
                </p>
                {section.scopes.map((key) => {
                  const meta = SCOPE_META[key];
                  const target = rules.tabs.find((t) => t.scope === key);
                  const editable = target?.editable ?? false;
                  const tabDirty = editable && !sameDraft(saved[key], draft[key]);
                  const tabErrors = editable ? errorsForScope(errors, key) : 0;
                  return (
                    <button
                      type="button"
                      key={key}
                      className="bp-secnav-item"
                      aria-current={key === scope}
                      onClick={() => setScope(key)}
                    >
                      <span className="bp-secnav-label">
                        {meta.short}
                        <small>{meta.scope}</small>
                      </span>
                      <span className="bp-state">
                        {tabErrors > 0 ? (
                          <span className="bz-badge is-danger">{plural(tabErrors, "error")}</span>
                        ) : tabDirty ? (
                          <span className="bz-badge is-warn">Unsaved</span>
                        ) : !editable ? (
                          <i className="bi bi-lock bz-lock" aria-label="Not editable yet" />
                        ) : null}
                      </span>
                    </button>
                  );
                })}
              </div>
            ))}
            <p className="bp-secnav-note">
              <i className="bi bi-flag" aria-hidden="true" />
              Bookings outside these rules are flagged for review, not blocked.
            </p>
          </nav>

          <section className="bz-card bp-sec">
            <div className="bz-card-head bp-sec-head">
              <div className="bp-sec-title">
                <span className="bz-icon-tile" aria-hidden="true">
                  <i className={`bi ${SCOPE_META[scope].icon}`} />
                </span>
                <div>
                  <h2 className="bz-card-title">{tab?.label ?? SCOPE_META[scope].short}</h2>
                  <p className="bz-card-sub">{SCOPE_META[scope].scope}</p>
                </div>
              </div>
              {tab?.editable && !sameDraft(scopeSaved, scopeDraft) && (
                <button type="button" className="bz-link" onClick={resetScope}>
                  <i className="bi bi-arrow-counterclockwise" aria-hidden="true" />
                  Reset section
                </button>
              )}
            </div>

            {tab?.editable ? (
              <RuleTiles
                scope={scope}
                settings={tab.settings}
                draft={scopeDraft}
                errors={errors}
                token={token}
                onChange={update}
              />
            ) : (
              /* All four tabs are authorable since LEIS-993, so this is
                 unreachable today. Kept rather than deleted: it is what a
                 future product tab (rail, car) renders as before its rules
                 exist, and the server already tells us per tab via `editable`. */
              <div className="bp-empty">
                <i className="bi bi-lock" aria-hidden="true" />
                <strong>These rules are not editable yet</strong>
                <span>
                  {tab?.label ?? "These"} rules will be editable here once the booking flow for
                  them ships.
                </span>
              </div>
            )}
          </section>

          <aside className="bz-card bp-live" aria-label="Traveler view" aria-live="polite">
            <div className="bp-live-head">
              <span className="bp-live-eye" aria-hidden="true">
                <i className="bi bi-phone" />
              </span>
              <div>
                <h2 className="bp-live-title">Traveler view</h2>
                <p>
                  What {group.name} travelers see for {(tab?.label ?? "").toLowerCase()}
                </p>
              </div>
            </div>

            {tab?.editable ? (
              <>
                <dl className="bp-live-list">
                  {travellerRowsFor(scope).map((row) => {
                    const changed = row.settings.some(
                      (key) =>
                        JSON.stringify(scopeSaved[key] ?? null) !==
                        JSON.stringify(scopeDraft[key] ?? null)
                    );
                    const bad = row.settings.some((key) => errors[`${scope}.${key}`]);
                    return (
                      <div key={row.label} className={changed ? "is-changed" : undefined}>
                        <dt>{row.label}</dt>
                        <dd>
                          {bad ? (
                            <span className="bp-live-err">
                              <i className="bi bi-exclamation-circle" aria-hidden="true" />
                              Fix this rule to preview it
                            </span>
                          ) : (
                            <>
                              {row.render(scopeDraft)}
                              {changed && <span className="bz-badge is-warn">Unsaved</span>}
                            </>
                          )}
                        </dd>
                      </div>
                    );
                  })}
                </dl>
                <button
                  type="button"
                  className="bz-btn bz-btn-secondary bz-btn-sm bp-live-btn"
                  onClick={() => setSummaryOpen(true)}
                >
                  <i className="bi bi-layout-text-window" aria-hidden="true" />
                  Full summary
                </button>
              </>
            ) : (
              <p className="bp-sub">Nothing to preview on this tab yet.</p>
            )}
          </aside>
        </div>
      </div>

      {/* ── the save dock ────────────────────────────────────────────────── */}
      {dirty && (
        <div className="bz-ui bz-dock" role="region" aria-label="Unsaved changes">
          <span className={cx("bz-dock-text", errorCount > 0 && "is-error")} role="status">
            {errorCount > 0
              ? `Fix ${plural(errorCount, "error")} to save`
              : plural(diffs.length, "unsaved change")}
          </span>
          <div className="bz-dock-actions">
            <button
              type="button"
              className="bz-btn bz-btn-ghost"
              onClick={() => setDiscarding(true)}
              disabled={submitting}
            >
              Discard
            </button>
            <button
              type="button"
              className="bz-btn bz-btn-primary"
              onClick={() => setConfirming(true)}
              disabled={errorCount > 0 || submitting}
            >
              <i className="bi bi-check2" aria-hidden="true" />
              <span>Save changes</span>
            </button>
          </div>
        </div>
      )}

      {/* ── dialogs ──────────────────────────────────────────────────────── */}
      {menu && (
        <GroupMenu
          anchor={menu}
          group={group}
          context="editor"
          onSelect={onMenuSelect}
          onClose={() => setMenu(null)}
        />
      )}

      {confirming && (
        <SaveChangesModal
          groupName={group.name}
          memberCount={memberCount}
          diffs={diffs}
          submitting={submitting}
          onClose={() => setConfirming(false)}
          onConfirm={() => void commit()}
        />
      )}

      {discarding && (
        <DiscardChangesModal
          groupName={group.name}
          onClose={() => setDiscarding(false)}
          onDiscard={() => {
            setDraft(saved);
            setServerErrors({});
            setDiscarding(false);
            toast.success("Changes discarded.");
          }}
        />
      )}

      {pendingHref && (
        <LeaveGuardModal
          groupName={group.name}
          onStay={() => setPendingHref(null)}
          onLeave={() => {
            const href = pendingHref;
            setPendingHref(null);
            leaveTo(href);
          }}
        />
      )}

      {summaryOpen && (
        <TravelerSummaryDrawer
          groupName={group.name}
          tabs={rules.tabs}
          saved={saved}
          draft={draft}
          onClose={() => setSummaryOpen(false)}
        />
      )}

      {logOpen && (
        <ChangeLogDrawer
          token={token}
          groups={groups}
          initialGroupId={groupId}
          onClose={() => setLogOpen(false)}
        />
      )}

      {managing && (
        <ManageMembersDrawer
          token={token}
          group={{ id: groupId, name: group.name }}
          onClose={() => setManaging(false)}
          onSaved={async () => {
            setManaging(false);
            const overview = await fetchOverview(token);
            if (overview.success && overview.data) setGroups(overview.data.groups);
          }}
        />
      )}

      {renaming && card && (
        <RenameGroupModal
          token={token}
          group={card}
          groups={groups}
          onClose={() => setRenaming(false)}
          onRenamed={() => {
            setRenaming(false);
            void load();
          }}
        />
      )}

      {duplicating && card && (
        <DuplicateGroupModal
          token={token}
          group={card}
          groups={groups}
          onClose={() => setDuplicating(false)}
          onDuplicated={() => {
            setDuplicating(false);
            router.push("/admin/travel-policy");
          }}
        />
      )}

      {deleting && card && (
        <DeleteGroupModal
          token={token}
          group={card}
          groups={groups}
          onClose={() => setDeleting(false)}
          onDeleted={() => {
            setDeleting(false);
            // The group this page is editing is gone, so there is nothing to
            // guard and nowhere to stay.
            dirtyRef.current = false;
            router.push("/admin/travel-policy");
          }}
        />
      )}
    </section>
  );
}
