"use client";

import { useEffect, useMemo, useState } from "react";
import { apiGet } from "@/lib/api";

type CheckoutAuditResult = {
  id: string;
  action: string;
  resultStatus: string;
  createdAt: string;
  actorEmail: string | null;
  workspaceId: string | null;
  workspaceName: string | null;
  workspaceSlug: string | null;
  workspaceType: string | null;
  planName: string | null;
  summary: string;
  checkoutSessionCreated: boolean;
  checkoutSessionIdMasked: string | null;
  checkoutSessionUrlReturned: boolean;
  checkoutSessionUrlWithheld: boolean;
  paymentStatus: string | null;
  sessionStatus: string | null;
  customerIdMasked: string | null;
  monthlyPriceIdMasked: string | null;
  lockReason: string | null;
  firstFix: string;
  guardrails: {
    checkoutSessionCreated: boolean;
    cardCollectionStartedByApp: boolean;
    checkoutUrlReturned: boolean;
    customerPortalSessionCreated: boolean;
    invoiceOrChargeCreatedByApp: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

type ApprovalHistoryEvent = {
  id: string;
  switchKey: string;
  label: string;
  state: string;
  approved: boolean;
  revoked: boolean;
  note: string;
  reviewedAt: string;
  reviewedBy: string | null;
  readinessStatus: string;
  canApproveAtReview: boolean | null;
  summary: string;
};

type StripeCheckoutAuditReview = {
  summary: {
    checkoutAuditEvents: number;
    lockedReviewEvents: number;
    lockedTestSessionCreatedEvents: number;
    checkoutUrlReturnedEvents: number;
    urlWithheldEvents: number;
    approvalHistoryEvents: number;
    approvalApprovedEvents: number;
    approvalRevokedEvents: number;
    guardrailWarnings: number;
    latestCheckoutAuditAt: string | null;
    latestApprovalAt: string | null;
  };
  checkoutResults: CheckoutAuditResult[];
  approvalHistory: ApprovalHistoryEvent[];
  guardrails: {
    auditOnly: boolean;
    checkoutUrlsReturnedByDefault: boolean;
    paymentCollectionActive: boolean;
    customerPortalActive: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

const workspaceTypeLabels: Record<string, string> = {
  DISPATCHER: "Dispatcher",
  COMPANY_FLEET: "Company / Fleet",
  CARRIER_OWNER_OPERATOR: "Carrier / Owner-Operator",
  FREIGHT_BROKER: "Freight Broker",
};

function dateTime(value?: string | null) {
  if (!value) return "Not recorded";
  return new Date(value).toLocaleString();
}

function labelWorkspaceType(value?: string | null) {
  if (!value) return "Unclassified";
  return workspaceTypeLabels[value] ?? value.split("_").map((part) => `${part.charAt(0)}${part.slice(1).toLowerCase()}`).join(" ");
}

function csvEscape(value: unknown) {
  const text = String(value ?? "");
  if (/[",\n]/.test(text)) return `"${text.replace(/"/g, '""')}"`;
  return text;
}

function downloadCsv(filename: string, headers: string[], rows: unknown[][]) {
  const csv = [headers, ...rows].map((row) => row.map(csvEscape).join(",")).join("\n");
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);
}

function checkoutSearchText(event: CheckoutAuditResult) {
  return [
    event.resultStatus,
    event.action,
    event.workspaceName,
    event.workspaceSlug,
    event.workspaceType,
    event.planName,
    event.actorEmail,
    event.checkoutSessionIdMasked,
    event.customerIdMasked,
    event.monthlyPriceIdMasked,
    event.summary,
    event.lockReason,
    event.firstFix,
  ].filter(Boolean).join(" ").toLowerCase();
}

function approvalSearchText(event: ApprovalHistoryEvent) {
  return [
    event.switchKey,
    event.label,
    event.state,
    event.note,
    event.reviewedBy,
    event.readinessStatus,
    event.summary,
  ].filter(Boolean).join(" ").toLowerCase();
}

export function AdminStripeCheckoutAuditReviewPanel() {
  const [review, setReview] = useState<StripeCheckoutAuditReview | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [checkoutFilter, setCheckoutFilter] = useState("all");
  const [approvalFilter, setApprovalFilter] = useState("all");
  const [switchFilter, setSwitchFilter] = useState("all");
  const [search, setSearch] = useState("");

  useEffect(() => {
    let cancelled = false;

    async function loadReview() {
      try {
        setError(null);
        const data = await apiGet<StripeCheckoutAuditReview>("/api/admin/stripe-checkout/audit-review");
        if (!cancelled) setReview(data);
      } catch (err: any) {
        if (!cancelled) setError(err?.message ?? "Failed to load checkout audit review.");
      } finally {
        if (!cancelled) setLoaded(true);
      }
    }

    void loadReview();

    return () => {
      cancelled = true;
    };
  }, []);

  const switchOptions = useMemo(() => {
    const keys = new Set<string>();
    review?.approvalHistory.forEach((event) => {
      if (event.switchKey) keys.add(event.switchKey);
    });
    return Array.from(keys).sort();
  }, [review]);

  const filteredCheckoutResults = useMemo(() => {
    const needle = search.trim().toLowerCase();
    return (review?.checkoutResults ?? []).filter((event) => {
      const matchesFilter = checkoutFilter === "all"
        || (checkoutFilter === "created" && event.checkoutSessionCreated)
        || (checkoutFilter === "reviewed" && !event.checkoutSessionCreated)
        || (checkoutFilter === "url-returned" && event.checkoutSessionUrlReturned)
        || (checkoutFilter === "url-withheld" && event.checkoutSessionCreated && !event.checkoutSessionUrlReturned);
      const matchesSearch = !needle || checkoutSearchText(event).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, checkoutFilter, search]);

  const filteredApprovalHistory = useMemo(() => {
    const needle = search.trim().toLowerCase();
    return (review?.approvalHistory ?? []).filter((event) => {
      const matchesState = approvalFilter === "all"
        || (approvalFilter === "approved" && event.approved)
        || (approvalFilter === "revoked" && event.revoked)
        || (approvalFilter === "reviewed" && !event.approved && !event.revoked);
      const matchesSwitch = switchFilter === "all" || event.switchKey === switchFilter;
      const matchesSearch = !needle || approvalSearchText(event).includes(needle);
      return matchesState && matchesSwitch && matchesSearch;
    });
  }, [review, approvalFilter, switchFilter, search]);

  function exportCheckoutResults() {
    downloadCsv(
      "dispatchspot-stripe-checkout-locked-test-results.csv",
      ["Created", "Result", "Workspace", "Workspace type", "Plan", "Session created", "Session ID", "URL returned", "Payment status", "Session status", "Actor", "First fix", "Summary"],
      filteredCheckoutResults.map((event) => [
        dateTime(event.createdAt),
        event.resultStatus,
        event.workspaceName ?? "",
        labelWorkspaceType(event.workspaceType),
        event.planName ?? "",
        event.checkoutSessionCreated ? "yes" : "no",
        event.checkoutSessionIdMasked ?? "",
        event.checkoutSessionUrlReturned ? "yes" : "no",
        event.paymentStatus ?? "",
        event.sessionStatus ?? "",
        event.actorEmail ?? "",
        event.firstFix,
        event.summary,
      ]),
    );
  }

  function exportApprovalHistory() {
    downloadCsv(
      "dispatchspot-stripe-checkout-approval-history.csv",
      ["Reviewed", "Switch", "State", "Readiness", "Can approve at review", "Reviewed by", "Note", "Summary"],
      filteredApprovalHistory.map((event) => [
        dateTime(event.reviewedAt),
        event.label,
        event.state,
        event.readinessStatus,
        event.canApproveAtReview === null ? "" : event.canApproveAtReview ? "yes" : "no",
        event.reviewedBy ?? "",
        event.note,
        event.summary,
      ]),
    );
  }

  if (!loaded) {
    return <section className="rounded-2xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Loading checkout audit review...</section>;
  }

  if (error) {
    return <section className="rounded-2xl border border-rose-100 bg-rose-50 p-6 text-sm text-rose-700 shadow-sm">{error}</section>;
  }

  if (!review) {
    return <section className="rounded-2xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Checkout audit review is not available yet.</section>;
  }

  const guardrailsClean = review.guardrails.auditOnly
    && !review.guardrails.checkoutUrlsReturnedByDefault
    && !review.guardrails.paymentCollectionActive
    && !review.guardrails.customerPortalActive
    && !review.guardrails.hardBillingGatesChanged
    && !review.guardrails.brokerDistributionChanged
    && !review.guardrails.ownedPortalRulesChanged
    && !review.guardrails.internalLoadBoardAccessChanged;

  return (
    <section className="rounded-2xl border border-sky-100 bg-sky-50 p-6 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-sky-700">Stripe checkout audit</div>
          <h2 className="mt-1 text-lg font-semibold text-slate-900">Locked test-session result review and approval history</h2>
          <p className="mt-1 max-w-4xl text-sm leading-6 text-sky-900">
            This panel lets Super Admin review locked checkout POST attempts, masked Stripe test-session results, approval-switch history, and export filtered records. It does not return checkout URLs, collect cards, open the customer portal, or change billing access.
          </p>
        </div>
        <span className={`w-fit rounded-full px-3 py-1 text-xs font-semibold ${guardrailsClean ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}`}>
          {guardrailsClean ? "Audit-only guardrails clean" : "Review audit guardrails"}
        </span>
      </div>

      <div className="mt-5 grid gap-3 text-sm md:grid-cols-4 xl:grid-cols-8">
        <div className="rounded-xl border border-sky-100 bg-white p-3"><div className="text-xs text-slate-500">Checkout audit</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.checkoutAuditEvents}</div></div>
        <div className="rounded-xl border border-sky-100 bg-white p-3"><div className="text-xs text-slate-500">Locked reviews</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.lockedReviewEvents}</div></div>
        <div className="rounded-xl border border-sky-100 bg-white p-3"><div className="text-xs text-slate-500">Test sessions</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.lockedTestSessionCreatedEvents}</div></div>
        <div className="rounded-xl border border-sky-100 bg-white p-3"><div className="text-xs text-slate-500">URLs withheld</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.urlWithheldEvents}</div></div>
        <div className="rounded-xl border border-sky-100 bg-white p-3"><div className="text-xs text-slate-500">URLs returned</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.checkoutUrlReturnedEvents}</div></div>
        <div className="rounded-xl border border-sky-100 bg-white p-3"><div className="text-xs text-slate-500">Approval events</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.approvalHistoryEvents}</div></div>
        <div className="rounded-xl border border-sky-100 bg-white p-3"><div className="text-xs text-slate-500">Revoked</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.approvalRevokedEvents}</div></div>
        <div className="rounded-xl border border-sky-100 bg-white p-3"><div className="text-xs text-slate-500">Warnings</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.guardrailWarnings}</div></div>
      </div>

      <div className="mt-5 rounded-2xl border border-sky-100 bg-white p-4">
        <div className="flex flex-col gap-3 xl:flex-row xl:items-end xl:justify-between">
          <div>
            <h3 className="font-semibold text-slate-900">Audit filters and exports</h3>
            <p className="mt-1 text-sm leading-6 text-slate-500">The search applies to both checkout results and approval history.</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <button type="button" onClick={exportCheckoutResults} className="rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white">Export checkout results CSV</button>
            <button type="button" onClick={exportApprovalHistory} className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-700">Export approval history CSV</button>
          </div>
        </div>
        <div className="mt-4 grid gap-3 lg:grid-cols-4">
          <label className="text-sm font-medium text-slate-700">
            Checkout result
            <select value={checkoutFilter} onChange={(event) => setCheckoutFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none focus:border-sky-300">
              <option value="all">All checkout records</option>
              <option value="created">Locked test sessions created</option>
              <option value="reviewed">Locked review only</option>
              <option value="url-withheld">Session created, URL withheld</option>
              <option value="url-returned">URL returned</option>
            </select>
          </label>
          <label className="text-sm font-medium text-slate-700">
            Approval state
            <select value={approvalFilter} onChange={(event) => setApprovalFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none focus:border-sky-300">
              <option value="all">All approval records</option>
              <option value="approved">Approved</option>
              <option value="revoked">Revoked</option>
              <option value="reviewed">Reviewed only</option>
            </select>
          </label>
          <label className="text-sm font-medium text-slate-700">
            Approval switch
            <select value={switchFilter} onChange={(event) => setSwitchFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none focus:border-sky-300">
              <option value="all">All switches</option>
              {switchOptions.map((key) => <option key={key} value={key}>{key}</option>)}
            </select>
          </label>
          <label className="text-sm font-medium text-slate-700">
            Search
            <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Workspace, plan, switch, actor, note..." className="mt-1 w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none focus:border-sky-300" />
          </label>
        </div>
        <div className="mt-3 flex flex-wrap gap-2 text-xs text-slate-600">
          <span className="rounded-full bg-slate-100 px-3 py-1">Checkout records shown: {filteredCheckoutResults.length}</span>
          <span className="rounded-full bg-slate-100 px-3 py-1">Approval records shown: {filteredApprovalHistory.length}</span>
          <button type="button" onClick={() => { setCheckoutFilter("all"); setApprovalFilter("all"); setSwitchFilter("all"); setSearch(""); }} className="rounded-full border border-slate-200 bg-white px-3 py-1 font-semibold text-slate-700">Reset filters</button>
        </div>
      </div>

      <div className="mt-5 grid gap-4 xl:grid-cols-2">
        <div className="rounded-2xl border border-sky-100 bg-white p-4">
          <h3 className="font-semibold text-slate-900">Locked checkout test-session results</h3>
          <div className="mt-3 space-y-3">
            {filteredCheckoutResults.slice(0, 12).map((event) => (
              <div key={event.id} className="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-sm leading-6 text-slate-600">
                <div className="flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
                  <div>
                    <div className="font-semibold text-slate-900">{event.resultStatus}</div>
                    <div className="text-xs text-slate-500">{dateTime(event.createdAt)}{event.actorEmail ? ` by ${event.actorEmail}` : ""}</div>
                  </div>
                  <span className={`w-fit rounded-full px-2 py-1 text-xs font-semibold ${event.checkoutSessionCreated ? "bg-emerald-100 text-emerald-700" : "bg-slate-100 text-slate-700"}`}>{event.checkoutSessionCreated ? "Session created" : "Review only"}</span>
                </div>
                <div className="mt-3 grid gap-2 md:grid-cols-2">
                  <div className="rounded-xl bg-white p-3"><span className="font-semibold text-slate-900">Workspace:</span> {event.workspaceName ?? "Not recorded"}</div>
                  <div className="rounded-xl bg-white p-3"><span className="font-semibold text-slate-900">Type:</span> {labelWorkspaceType(event.workspaceType)}</div>
                  <div className="rounded-xl bg-white p-3"><span className="font-semibold text-slate-900">Plan:</span> {event.planName ?? "Not recorded"}</div>
                  <div className="rounded-xl bg-white p-3"><span className="font-semibold text-slate-900">Session:</span> {event.checkoutSessionIdMasked ?? "Not created"}</div>
                </div>
                <div className="mt-2 rounded-xl bg-white p-3 text-xs leading-5 text-slate-700"><span className="font-semibold text-slate-900">URL state:</span> {event.checkoutSessionUrlReturned ? "Returned by explicit flag" : event.checkoutSessionCreated ? "Withheld" : "No URL"}</div>
                <div className="mt-2 rounded-xl bg-white p-3 text-xs leading-5 text-slate-700"><span className="font-semibold text-slate-900">First fix:</span> {event.firstFix}</div>
              </div>
            ))}
            {!filteredCheckoutResults.length ? <div className="rounded-xl border border-slate-100 bg-slate-50 p-4 text-sm text-slate-500">No checkout audit records match these filters yet.</div> : null}
          </div>
        </div>

        <div className="rounded-2xl border border-sky-100 bg-white p-4">
          <h3 className="font-semibold text-slate-900">Approval-switch history</h3>
          <div className="mt-3 space-y-3">
            {filteredApprovalHistory.slice(0, 12).map((event) => (
              <div key={event.id} className="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-sm leading-6 text-slate-600">
                <div className="flex flex-col gap-2 lg:flex-row lg:items-start lg:justify-between">
                  <div>
                    <div className="font-semibold text-slate-900">{event.label}</div>
                    <div className="text-xs text-slate-500">{dateTime(event.reviewedAt)}{event.reviewedBy ? ` by ${event.reviewedBy}` : ""}</div>
                  </div>
                  <span className={`w-fit rounded-full px-2 py-1 text-xs font-semibold ${event.approved ? "bg-emerald-100 text-emerald-700" : event.revoked ? "bg-rose-100 text-rose-700" : "bg-slate-100 text-slate-700"}`}>{event.state}</span>
                </div>
                <div className="mt-2 rounded-xl bg-white p-3 text-xs leading-5 text-slate-700"><span className="font-semibold text-slate-900">Readiness:</span> {event.readinessStatus || "Not recorded"}</div>
                {event.note ? <div className="mt-2 rounded-xl bg-white p-3 text-xs leading-5 text-slate-700"><span className="font-semibold text-slate-900">Note:</span> {event.note}</div> : null}
              </div>
            ))}
            {!filteredApprovalHistory.length ? <div className="rounded-xl border border-slate-100 bg-slate-50 p-4 text-sm text-slate-500">No approval-switch records match these filters yet.</div> : null}
          </div>
        </div>
      </div>

      <div className="mt-4 rounded-xl border border-dashed border-sky-200 bg-white/70 p-3 text-xs leading-5 text-slate-600">
        Audit guardrails: checkout URL return stays locked by default, payment collection is off, customer portal sessions are off, hard billing gates are unchanged, broker distribution is unchanged, owned portal rules are unchanged, and internal load-board access is unchanged.
      </div>
    </section>
  );
}
