"use client";

import type { PolicyScope, PolicyTab } from "@/services/travel-policy/travel-policy.client";
import {
  EDITABLE_SCOPES,
  FLIGHT_SCOPES,
  HOTEL_SCOPES,
  HOTEL_TRAVELLER_ROWS,
  SCOPE_META,
  TRAVELLER_ROWS,
  plural,
  sameDraft,
  type DraftDiff,
  type PolicyDraft,
  type ScopeDraft,
} from "@/services/travel-policy/policy-format";

import PolicyOverlay, { PolicyDrawerHead, PolicyModalHead } from "./PolicyOverlay";

/* ── Save changes ──────────────────────────────────────────────────────────── */

/**
 * The confirmation before a policy save, listing every change as from → to.
 *
 * Worth a dialog rather than a bare Save because of what the sub-line says: the
 * new rules apply to new searches and requests, and requests already submitted
 * keep the results they were judged with. An admin tightening a fare cap to fix
 * a request already in their queue needs to know it will not reach that one.
 *
 * The list is grouped by tab, so a two-tab save reads as two decisions rather
 * than one undifferentiated pile.
 */
export function SaveChangesModal({
  groupName,
  memberCount,
  diffs,
  submitting,
  onClose,
  onConfirm,
}: {
  groupName: string;
  memberCount: number;
  diffs: readonly DraftDiff[];
  submitting: boolean;
  onClose: () => void;
  onConfirm: () => void;
}) {
  // Every editable tab. This used to walk FLIGHT_SCOPES, which would have
  // silently omitted a changed hotel tab from the confirmation the admin reads
  // before saving it.
  const byTab = EDITABLE_SCOPES.map((scope) => ({
    scope,
    rows: diffs.filter((d) => d.scope === scope),
  })).filter((entry) => entry.rows.length > 0);

  return (
    <PolicyOverlay
      label={`Save changes to ${groupName}?`}
      width={580}
      onClose={onClose}
      busy={submitting}
    >
      <PolicyModalHead
        icon="bi-check2-circle"
        tone="green"
        title={<>Save changes to {groupName}?</>}
        sub="New rules apply to new searches and requests. Requests already submitted keep their current policy results."
      />
      <div className="bz-modal-body">
        <div className="bp-diff">
          {byTab.map(({ scope, rows }) => (
            <div className="bp-diff-group" key={scope}>
              <h4>
                <i className={`bi ${SCOPE_META[scope].icon}`} aria-hidden="true" />
                {rows[0].scopeLabel}
              </h4>
              <ul>
                {rows.map((row) => (
                  <li key={`${scope}.${row.setting}`}>
                    <span className="bp-diff-label">{row.label}</span>
                    <span className="bp-diff-vals">
                      <span className="bp-diff-from">{row.from}</span>
                      <i className="bi bi-arrow-right" aria-label="changes to" />
                      <strong>{row.to}</strong>
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </div>
      <div className="bz-modal-foot">
        <span className="bz-modal-note">
          {plural(diffs.length, "change")} · affects {plural(memberCount, "traveler")}
        </span>
        <button
          type="button"
          className="bz-btn bz-btn-secondary"
          onClick={onClose}
          disabled={submitting}
        >
          Cancel
        </button>
        <button
          type="button"
          className="bz-btn bz-btn-primary"
          onClick={onConfirm}
          disabled={submitting}
        >
          {submitting ? "Saving…" : "Save changes"}
        </button>
      </div>
    </PolicyOverlay>
  );
}

/* ── Discard ───────────────────────────────────────────────────────────────── */

export function DiscardChangesModal({
  groupName,
  onClose,
  onDiscard,
}: {
  groupName: string;
  onClose: () => void;
  onDiscard: () => void;
}) {
  return (
    <PolicyOverlay label="Discard changes?" width={460} onClose={onClose}>
      <PolicyModalHead
        icon="bi-arrow-counterclockwise"
        tone="coral"
        title="Discard changes?"
        sub={`Your unsaved changes to ${groupName} will be lost.`}
      />
      <div className="bz-modal-foot">
        <button type="button" className="bz-btn bz-btn-secondary" onClick={onClose} autoFocus>
          Keep editing
        </button>
        <button type="button" className="bz-btn bz-btn-danger" onClick={onDiscard}>
          Discard
        </button>
      </div>
    </PolicyOverlay>
  );
}

/* ── Leave guard ───────────────────────────────────────────────────────────── */

/**
 * "Leave without saving?" (PRD §8.5).
 *
 * Raised by the editor's own navigation guard, which intercepts in-page link
 * clicks. `beforeunload` covers a reload or a closed tab, but it can only show
 * the browser's own generic prompt — this is the in-app half, and the only one
 * that can name the group.
 */
export function LeaveGuardModal({
  groupName,
  onStay,
  onLeave,
}: {
  groupName: string;
  onStay: () => void;
  onLeave: () => void;
}) {
  return (
    <PolicyOverlay label="Leave without saving?" width={460} onClose={onStay}>
      <PolicyModalHead
        icon="bi-exclamation-triangle"
        tone="amber"
        title="Leave without saving?"
        sub={`Your changes to ${groupName} will be lost.`}
      />
      <div className="bz-modal-foot">
        <button type="button" className="bz-btn bz-btn-secondary" onClick={onStay} autoFocus>
          Stay
        </button>
        <button type="button" className="bz-btn bz-btn-danger" onClick={onLeave}>
          Discard changes
        </button>
      </div>
    </PolicyOverlay>
  );
}

/* ── Traveller summary ─────────────────────────────────────────────────────── */

/**
 * "What <group> travelers see" (PRD §8.5's Preview traveler summary).
 *
 * Both flight tabs side by side, in plain language rather than the admin's
 * control labels — a traveller never sees "ALLOWED_CABINS", they see "Economy,
 * Premium Economy". Unsaved edits are marked, because this opens from the
 * editor and would otherwise claim a policy that is not in force yet.
 *
 * The hotel tabs are deliberately absent: there are no hotel rules to describe
 * until the hotel evaluator exists, and an empty Hotels table would read as
 * "no hotel policy" rather than "not configured here yet".
 */

/**
 * One product's summary table — a column per tab, a row per traveller-facing
 * rule, with "Unsaved" where the draft differs from what is stored.
 *
 * A function rather than two copies of the markup: the flight and hotel tables
 * are the same table with a different row list, and the earlier version of this
 * drawer rendered flights only. Returns null for a product with no editable
 * tabs, so a future locked product simply does not appear.
 */
function productTable(args: {
  title: string;
  icon: string;
  productTabs: readonly PolicyTab[];
  rows: ReadonlyArray<{ label: string; settings: readonly string[]; render(d: ScopeDraft): string }>;
  saved: PolicyDraft;
  draft: PolicyDraft;
}) {
  const { title, icon, productTabs, rows, saved, draft } = args;
  if (productTabs.length === 0) return null;

  return (
    <>
      <h4 className="bp-sum-title">
        <i className={`bi ${icon}`} aria-hidden="true" />
        {title}
      </h4>
      <table className="bp-st">
        <thead>
          <tr>
            <th scope="col">
              <span className="bz-sr">Rule</span>
            </th>
            {productTabs.map((tab) => (
              <th scope="col" key={tab.scope}>
                {SCOPE_META[tab.scope].short}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => (
            <tr key={row.label}>
              <th scope="row">{row.label}</th>
              {productTabs.map((tab) => {
                const after = draft[tab.scope] ?? {};
                const before = saved[tab.scope] ?? {};
                const changed = row.settings.some(
                  (key) => JSON.stringify(before[key] ?? null) !== JSON.stringify(after[key] ?? null)
                );
                return (
                  <td key={tab.scope}>
                    {row.render(after)}
                    {changed ? <span className="bp-unsaved">Unsaved</span> : null}
                  </td>
                );
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}

export function TravelerSummaryDrawer({
  groupName,
  tabs,
  saved,
  draft,
  onClose,
}: {
  groupName: string;
  tabs: readonly PolicyTab[];
  saved: PolicyDraft;
  draft: PolicyDraft;
  onClose: () => void;
}) {
  const editable = (scopes: readonly PolicyScope[]) =>
    tabs.filter((t) => t.editable && scopes.includes(t.scope));
  const flightTabs = editable(FLIGHT_SCOPES);
  const hotelTabs = editable(HOTEL_SCOPES);
  const anyUnsaved = EDITABLE_SCOPES.some((scope) => !sameDraft(saved[scope], draft[scope]));

  return (
    <PolicyOverlay label={`What ${groupName} travelers see`} variant="drawer" onClose={onClose}>
      <PolicyDrawerHead title={`What ${groupName} travelers see`} onClose={onClose} />
      <div className="bz-modal-body bp-sum">
        <p className="bp-sum-intro">
          A plain summary of this group&rsquo;s rules, as shown to travelers.
          {anyUnsaved ? " Unsaved edits are marked." : ""}
        </p>

        {productTable({
          title: 'Flights',
          icon: 'bi-airplane-fill',
          productTabs: flightTabs,
          rows: TRAVELLER_ROWS,
          saved,
          draft,
        })}
        {productTable({
          title: 'Hotels',
          icon: 'bi-building-fill',
          productTabs: hotelTabs,
          rows: HOTEL_TRAVELLER_ROWS,
          saved,
          draft,
        })}

        <div className="bp-sum-note">
          Anything outside these rules can still be requested. It will be flagged for your review.
        </div>
      </div>
    </PolicyOverlay>
  );
}
