"use client";

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

type ApprovalStatus = "Ready" | "Check" | "Blocked" | "Locked";
type ScopeStatus = "Approved scope" | "Needs evidence" | "Blocked" | "Rollback held" | "Out of scope" | "Locked";

type BoundaryCheckRow = {
  key: string;
  label: string;
  status: ApprovalStatus;
  detail: string;
  firstFix: string;
  rolloutEffect: string;
};

type RolloutBoundaryItem = {
  key: string;
  boundary: string;
  status: ApprovalStatus;
  owner: string;
  instruction: string;
  evidenceNeeded: string;
};

type RolloutScopeRow = {
  workspaceId: string;
  subscriptionId: string;
  workspaceName: string;
  workspaceSlug: string;
  workspaceType: string;
  workspaceTypeLabel: string;
  accountClass: string;
  accountClassLabel: string;
  organizationActive: boolean;
  subscriptionStatus: string;
  planName: string;
  planStatus: string;
  billingProvider: string;
  billingMode: string;
  providerSyncStatus: string;
  configuredInScope: boolean;
  proposedForScope: boolean;
  previouslyPilotVerified: boolean;
  supportOutcomeStatus: string;
  closeoutStatus: string;
  safetyStatus: string;
  scopeStatus: ScopeStatus;
  scopeRisk: string;
  firstFix: string;
  rolloutInstruction: string;
};

type EvidenceEvent = {
  id: string;
  action: string;
  recordedAt: string | null;
  recordedBy: string;
  summary: string;
  note: string;
  approvalStatus: string;
  proposedScopeCount: number;
  approvedScopeCount: number;
  blockedScopeCount: number;
  rolloutLabel: string;
};

type Review = {
  summary: {
    overallStatus: ApprovalStatus;
    rolloutScopeLabel: string;
    totalReviewedWorkspaces: number;
    proposedScopeCount: number;
    approvedScopeCount: number;
    needsEvidenceCount: number;
    rollbackHeldCount: number;
    blockedScopeCount: number;
    outOfScopeCount: number;
    maxRolloutWorkspaces: number;
    configuredScopeCount: number;
    approvalBoundaryReviewCount: number;
    rolloutScopeReviewCount: number;
    supportOutcomeReviewCount: number;
    finalExpansionReviewCount: number;
    evidenceChainCount: number;
    canRecordApprovalBoundary: boolean;
    canRecordRolloutScope: boolean;
    rolloutScopeExportRequired: boolean;
    readyForLaterActivationBuild: boolean;
    firstFix: string;
  };
  environment: {
    expansionApprovalEnabled: boolean;
    rolloutScopeReviewEnabled: boolean;
    rolloutScopeExportRequired: boolean;
    rolloutScopeLabel: string;
    configuredScopeIdentifiers: string[];
    maxRolloutWorkspaces: number;
    controlledActivationEnabled: boolean;
    controlledActivationReviewOnly: boolean;
    rollbackActive: boolean;
    broadHardBillingGatesEnabled: boolean;
    paymentCollectionEnabled: boolean;
    billingStatusMutationEnabled: boolean;
    customerPortalEnabled: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
  checks: BoundaryCheckRow[];
  rolloutBoundary: RolloutBoundaryItem[];
  rolloutScopeRows: RolloutScopeRow[];
  recentEvents: EvidenceEvent[];
};

function statusClasses(status: ApprovalStatus | ScopeStatus | string) {
  if (status === "Ready" || status === "Approved scope") return "bg-emerald-100 text-emerald-700";
  if (status === "Blocked" || status === "Rollback held") return "bg-rose-100 text-rose-700";
  if (status === "Locked" || status === "Out of scope") return "bg-blue-100 text-blue-700";
  return "bg-amber-100 text-amber-700";
}

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

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 rowText(row: RolloutScopeRow) {
  return [
    row.workspaceName,
    row.workspaceSlug,
    row.workspaceTypeLabel,
    row.accountClassLabel,
    row.subscriptionStatus,
    row.planName,
    row.planStatus,
    row.providerSyncStatus,
    row.supportOutcomeStatus,
    row.scopeStatus,
    row.scopeRisk,
    row.firstFix,
  ].join(" ").toLowerCase();
}

export function AdminHardBillingGateExpansionApprovalPanel() {
  const [review, setReview] = useState<Review | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState("proposed");
  const [search, setSearch] = useState("");
  const [note, setNote] = useState("");
  const [saving, setSaving] = useState<"approval-boundary" | "rollout-scope" | null>(null);

  async function loadReview() {
    const data = await apiGet<Review>("/api/admin/hard-billing-gates/expansion-approval");
    setReview(data);
  }

  useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        setError(null);
        const data = await apiGet<Review>("/api/admin/hard-billing-gates/expansion-approval");
        if (!cancelled) setReview(data);
      } catch (err: any) {
        if (!cancelled) setError(err?.message ?? "Failed to load hard billing gate expansion approval review.");
      } finally {
        if (!cancelled) setLoaded(true);
      }
    }
    void load();
    return () => {
      cancelled = true;
    };
  }, []);

  const needle = search.trim().toLowerCase();
  const rows = useMemo(() => {
    return (review?.rolloutScopeRows ?? []).filter((row) => {
      const matchesFilter = filter === "all"
        || row.scopeStatus === filter
        || row.subscriptionStatus === filter
        || row.providerSyncStatus === filter
        || row.workspaceType === filter
        || (filter === "proposed" && row.proposedForScope)
        || (filter === "configured" && row.configuredInScope)
        || (filter === "pilot-verified" && row.previouslyPilotVerified);
      const matchesSearch = !needle || rowText(row).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, filter, needle]);

  async function recordEvidence(recordType: "approval-boundary" | "rollout-scope") {
    try {
      setSaving(recordType);
      setError(null);
      const data = await apiPost<Review>("/api/admin/hard-billing-gates/expansion-approval", { note, recordType });
      setReview(data);
      setNote("");
    } catch (err: any) {
      setError(err?.message ?? "Failed to record hard billing gate expansion approval evidence.");
      await loadReview().catch(() => undefined);
    } finally {
      setSaving(null);
    }
  }

  function exportScopeRows() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-rollout-scope-review.csv",
      ["Workspace", "Slug", "Workspace type", "Account class", "Proposed", "Configured", "Scope status", "Scope risk", "Subscription", "Plan", "Plan status", "Provider sync", "Support outcome", "Closeout", "Safety", "First fix", "Instruction"],
      (review?.rolloutScopeRows ?? []).map((row) => [
        row.workspaceName,
        row.workspaceSlug,
        row.workspaceTypeLabel,
        row.accountClassLabel,
        row.proposedForScope ? "Yes" : "No",
        row.configuredInScope ? "Yes" : "No",
        row.scopeStatus,
        row.scopeRisk,
        row.subscriptionStatus,
        row.planName,
        row.planStatus,
        row.providerSyncStatus,
        row.supportOutcomeStatus,
        row.closeoutStatus,
        row.safetyStatus,
        row.firstFix,
        row.rolloutInstruction,
      ]),
    );
  }

  function exportBoundary() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-expansion-approval-boundary.csv",
      ["Boundary", "Status", "Owner", "Instruction", "Evidence needed"],
      (review?.rolloutBoundary ?? []).map((item) => [item.boundary, item.status, item.owner, item.instruction, item.evidenceNeeded]),
    );
  }

  function exportHistory() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-expansion-approval-history.csv",
      ["Recorded at", "Recorded by", "Action", "Approval status", "Rollout label", "Proposed", "Approved", "Blocked", "Summary", "Note"],
      (review?.recentEvents ?? []).map((event) => [
        dateTime(event.recordedAt),
        event.recordedBy,
        event.action,
        event.approvalStatus,
        event.rolloutLabel,
        event.proposedScopeCount,
        event.approvedScopeCount,
        event.blockedScopeCount,
        event.summary,
        event.note,
      ]),
    );
  }

  if (!loaded) {
    return <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm"><p className="text-sm text-slate-500">Loading hard billing gate expansion approval review…</p></section>;
  }

  if (!review) {
    return <section className="rounded-3xl border border-rose-200 bg-rose-50 p-6"><p className="text-sm text-rose-700">{error ?? "Hard billing gate expansion approval review is unavailable."}</p></section>;
  }

  const summary = review.summary;
  const env = review.environment;

  return (
    <section className="space-y-5 rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
      <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">v457 approval boundary and rollout scope</p>
          <h2 className="mt-1 text-xl font-semibold text-slate-950">Hard-gate expansion approval boundary</h2>
          <p className="mt-2 max-w-3xl text-sm text-slate-600">
            Super Admin can review the boundary for a later hard-gate expansion and export a proposed rollout scope. This is evidence only; it does not collect payment, mutate billing status, expand hard billing gates, change broker distribution, change owned portal rules, or open internal load-board access.
          </p>
        </div>
        <span className={`rounded-full px-3 py-1 text-xs font-semibold ${statusClasses(summary.overallStatus)}`}>{summary.overallStatus}</span>
      </div>

      {error ? <div className="rounded-2xl border border-rose-200 bg-rose-50 p-3 text-sm text-rose-700">{error}</div> : null}

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-6">
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Approval reviews</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.approvalBoundaryReviewCount}</p>
          <p className="text-xs text-slate-500">Recording {summary.canRecordApprovalBoundary ? "enabled" : "locked"}</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Scope reviews</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.rolloutScopeReviewCount}</p>
          <p className="text-xs text-slate-500">Recording {summary.canRecordRolloutScope ? "enabled" : "locked"}</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Proposed scope</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.proposedScopeCount}</p>
          <p className="text-xs text-slate-500">Max {summary.maxRolloutWorkspaces}</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Approved rows</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.approvedScopeCount}</p>
          <p className="text-xs text-slate-500">{summary.needsEvidenceCount + summary.rollbackHeldCount + summary.blockedScopeCount} need action</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Evidence chain</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.evidenceChainCount}</p>
          <p className="text-xs text-slate-500">pilot-to-scope records</p>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">First fix</p>
          <p className="mt-2 text-sm text-slate-700">{summary.firstFix}</p>
        </div>
      </div>

      <div className="rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900">
        <p className="font-semibold">Rollout boundary posture</p>
        <p className="mt-1">
          Scope label: {summary.rolloutScopeLabel}. Ready for later activation build: {summary.readyForLaterActivationBuild ? "yes" : "no"}. Export required: {summary.rolloutScopeExportRequired ? "yes" : "no"}. Rollback stop {env.rollbackActive ? "on" : "off"}. Broad hard gates {env.broadHardBillingGatesEnabled ? "on" : "off"}; payment collection {env.paymentCollectionEnabled ? "on" : "off"}; billing status mutation {env.billingStatusMutationEnabled ? "on" : "off"}; customer portal {env.customerPortalEnabled ? "on" : "off"}.
        </p>
      </div>

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
        {review.checks.map((item) => (
          <div key={item.key} className="rounded-2xl border border-slate-200 p-4">
            <div className="flex items-center justify-between gap-2">
              <p className="text-sm font-semibold text-slate-900">{item.label}</p>
              <span className={`rounded-full px-2 py-1 text-[11px] font-semibold ${statusClasses(item.status)}`}>{item.status}</span>
            </div>
            <p className="mt-2 text-xs text-slate-600">{item.detail}</p>
            <p className="mt-2 text-xs font-medium text-slate-700">{item.firstFix}</p>
            <p className="mt-2 text-[11px] text-slate-500">{item.rolloutEffect}</p>
          </div>
        ))}
      </div>

      <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <h3 className="text-sm font-semibold text-slate-950">Expansion approval boundary</h3>
            <p className="mt-1 text-xs text-slate-500">These boundaries prepare a later build decision. They do not widen the active hard-gate allowlist.</p>
          </div>
          <button className="rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-100" onClick={exportBoundary}>Export boundary checklist</button>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          {review.rolloutBoundary.map((item) => (
            <div key={item.key} className="rounded-xl border border-slate-200 bg-white p-4 text-xs text-slate-600">
              <div className="flex items-center justify-between gap-2">
                <p className="font-semibold text-slate-900">{item.boundary}</p>
                <span className={`rounded-full px-2 py-1 text-[11px] font-semibold ${statusClasses(item.status)}`}>{item.status}</span>
              </div>
              <p className="mt-1 text-slate-500">Owner: {item.owner}</p>
              <p className="mt-2">{item.instruction}</p>
              <p className="mt-2 font-medium text-slate-700">{item.evidenceNeeded}</p>
            </div>
          ))}
        </div>
      </div>

      <div className="flex flex-col gap-3 rounded-2xl border border-slate-200 bg-slate-50 p-4 lg:flex-row lg:items-center lg:justify-between">
        <div className="flex flex-wrap gap-2">
          <select className="rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm" value={filter} onChange={(event) => setFilter(event.target.value)}>
            <option value="proposed">Proposed scope</option>
            <option value="configured">Configured scope only</option>
            <option value="pilot-verified">Pilot verified</option>
            <option value="Approved scope">Approved scope</option>
            <option value="Needs evidence">Needs evidence</option>
            <option value="Rollback held">Rollback held</option>
            <option value="Blocked">Blocked</option>
            <option value="Out of scope">Out of scope</option>
            <option value="DISPATCHER">Dispatcher</option>
            <option value="COMPANY_FLEET">Company fleet</option>
            <option value="CARRIER_OWNER_OPERATOR">Carrier owner operator</option>
            <option value="FREIGHT_BROKER">Freight broker</option>
            <option value="all">All reviewed workspaces</option>
          </select>
          <input
            className="min-w-[260px] rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm"
            placeholder="Search workspace, scope status, plan, first fix…"
            value={search}
            onChange={(event) => setSearch(event.target.value)}
          />
        </div>
        <div className="flex flex-wrap gap-2">
          <button className="rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-100" onClick={exportScopeRows}>Export rollout scope</button>
          <button className="rounded-xl border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-100" onClick={exportHistory}>Export evidence history</button>
        </div>
      </div>

      <div className="overflow-x-auto rounded-2xl border border-slate-200">
        <table className="min-w-full divide-y divide-slate-200 text-sm">
          <thead className="bg-slate-50 text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
            <tr>
              <th className="px-4 py-3">Workspace</th>
              <th className="px-4 py-3">Scope status</th>
              <th className="px-4 py-3">Subscription</th>
              <th className="px-4 py-3">Pilot evidence</th>
              <th className="px-4 py-3">Instruction</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-200 bg-white">
            {rows.map((row) => (
              <tr key={row.workspaceId} className="align-top">
                <td className="px-4 py-3">
                  <p className="font-semibold text-slate-950">{row.workspaceName}</p>
                  <p className="text-xs text-slate-500">/{row.workspaceSlug}</p>
                  <p className="text-xs text-slate-500">{row.workspaceTypeLabel} · {row.accountClassLabel}</p>
                  <p className="text-xs text-slate-500">Configured: {row.configuredInScope ? "yes" : "no"} · Proposed: {row.proposedForScope ? "yes" : "no"}</p>
                </td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2 py-1 text-[11px] font-semibold ${statusClasses(row.scopeStatus)}`}>{row.scopeStatus}</span>
                  <p className="mt-2 text-xs text-slate-600">Risk: {row.scopeRisk}</p>
                </td>
                <td className="px-4 py-3 text-xs text-slate-600">
                  <p className="font-semibold text-slate-800">{row.subscriptionStatus}</p>
                  <p>{row.planName} · {row.planStatus}</p>
                  <p>{row.billingProvider} · {row.billingMode}</p>
                  <p>Provider sync: {row.providerSyncStatus}</p>
                  <p>Active workspace: {row.organizationActive ? "yes" : "no"}</p>
                </td>
                <td className="px-4 py-3 text-xs text-slate-600">
                  <p>Support: {row.supportOutcomeStatus}</p>
                  <p>Closeout: {row.closeoutStatus}</p>
                  <p>Safety: {row.safetyStatus}</p>
                  <p>Pilot verified: {row.previouslyPilotVerified ? "yes" : "no"}</p>
                </td>
                <td className="px-4 py-3 text-xs leading-5 text-slate-600">
                  <p>{row.rolloutInstruction}</p>
                  <p className="mt-2 font-medium text-slate-700">{row.firstFix}</p>
                </td>
              </tr>
            ))}
            {!rows.length ? (
              <tr>
                <td className="px-4 py-6 text-center text-sm text-slate-500" colSpan={5}>No rollout scope rows match this filter.</td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </div>

      <div className="grid gap-4 lg:grid-cols-[1fr_2fr]">
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <h3 className="text-sm font-semibold text-slate-950">Record approval evidence</h3>
          <p className="mt-1 text-xs text-slate-500">Recording evidence does not change environment flags, collect payment, widen hard gates, or change access rules.</p>
          <textarea
            className="mt-3 min-h-[92px] w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
            placeholder="Optional approval boundary or rollout scope note"
            value={note}
            onChange={(event) => setNote(event.target.value)}
          />
          <div className="mt-3 flex flex-wrap gap-2">
            <button
              className="rounded-xl bg-slate-950 px-4 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300"
              disabled={Boolean(saving) || !summary.canRecordApprovalBoundary}
              onClick={() => recordEvidence("approval-boundary")}
            >
              {saving === "approval-boundary" ? "Recording…" : "Record approval boundary"}
            </button>
            <button
              className="rounded-xl border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-100 disabled:cursor-not-allowed disabled:border-slate-200 disabled:text-slate-400"
              disabled={Boolean(saving) || !summary.canRecordRolloutScope}
              onClick={() => recordEvidence("rollout-scope")}
            >
              {saving === "rollout-scope" ? "Recording…" : "Record rollout scope review"}
            </button>
          </div>
          {!summary.canRecordApprovalBoundary || !summary.canRecordRolloutScope ? <p className="mt-2 text-xs text-slate-500">One or more recording switches are locked by environment flag.</p> : null}
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <h3 className="text-sm font-semibold text-slate-950">Recent approval evidence</h3>
          <div className="mt-3 grid gap-2 md:grid-cols-2">
            {(review.recentEvents ?? []).slice(0, 8).map((event) => (
              <div key={event.id} className="rounded-xl border border-slate-200 bg-white p-3 text-xs text-slate-600">
                <p className="font-semibold text-slate-900">{event.summary}</p>
                <p>{dateTime(event.recordedAt)} by {event.recordedBy}</p>
                <p>{event.action}</p>
                <p>Status: {event.approvalStatus || "not set"} · Label: {event.rolloutLabel || "not set"}</p>
                <p>Proposed: {event.proposedScopeCount} · Approved: {event.approvedScopeCount} · Blocked: {event.blockedScopeCount}</p>
                {event.note ? <p className="mt-1 text-slate-700">{event.note}</p> : null}
              </div>
            ))}
            {!review.recentEvents.length ? <p className="text-xs text-slate-500">No expansion approval evidence has been recorded yet.</p> : null}
          </div>
        </div>
      </div>
    </section>
  );
}
