"use client";

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

type PilotStatus = "Ready" | "Check" | "Blocked" | "Locked";
type SelectionState = "Selected" | "Not selected" | "Removed" | "Locked";

type CheckRow = {
  key: string;
  label: string;
  status: PilotStatus;
  detail: string;
  firstFix: string;
};

type WorkspaceRow = {
  workspaceId: string;
  workspaceName: string;
  workspaceSlug: string;
  isActive: boolean;
  workspaceTypeLabel: string;
  accountClassLabel: string;
  subscriptionStatusLabel: string;
  planName: string;
  providerSyncStatus: string;
  billingMode: string;
  hardGateReadinessStatus: string;
  softWarningSeverity: string;
  softWarningTitle: string;
  softWarningCount: number;
  overLimitCount: number;
  missingAddOnPriceCount: number;
  eligibilityStatus: PilotStatus;
  eligibilityLabel: string;
  eligibilityReason: string;
  firstFix: string;
  selected: boolean;
  selectedByReview: boolean;
  selectedByEnvironment: boolean;
  selectionState: SelectionState;
  lastReviewedAt: string | null;
  lastReviewedBy: string | null;
  latestNote: string;
  pilotEffect: string;
};

type PilotEvent = {
  id: string;
  workspaceId: string;
  workspaceName: string;
  selected: boolean;
  note: string;
  readinessStatus: string;
  pilotEffect: string;
  reviewedAt: string | null;
  reviewedBy: string;
  summary: string;
};

type Review = {
  summary: {
    overallStatus: PilotStatus;
    totalWorkspaces: number;
    readyCandidateCount: number;
    checkCandidateCount: number;
    blockedCandidateCount: number;
    lockedCandidateCount: number;
    selectedPilotCount: number;
    selectedReadyCount: number;
    selectedNeedsReviewCount: number;
    pilotEvents: number;
    canConsiderPilotActivationLater: boolean;
    firstFix: string;
  };
  environment: {
    pilotReadinessEnabled: boolean;
    pilotReviewOnly: boolean;
    hardBillingGatesEnabled: boolean;
    paymentCollectionEnabled: boolean;
    billingStatusMutationEnabled: boolean;
    customerPortalEnabled: boolean;
    trialToPaidReviewOnly: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
    envAllowlist: string[];
  };
  checks: CheckRow[];
  workspaceRows: WorkspaceRow[];
  recentEvents: PilotEvent[];
  guardrails: {
    readinessOnly: boolean;
    auditEvidenceOnly: boolean;
    hardBillingGatesActive: boolean;
    hardBillingGatePilotActive: boolean;
    workspaceAccessChanged: boolean;
    paymentCollectionActive: boolean;
    billingStatusMutationActive: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

function statusClasses(status: PilotStatus) {
  if (status === "Ready") return "bg-emerald-100 text-emerald-700";
  if (status === "Blocked") return "bg-rose-100 text-rose-700";
  if (status === "Locked") return "bg-blue-100 text-blue-700";
  return "bg-amber-100 text-amber-700";
}

function selectionClasses(state: SelectionState) {
  if (state === "Selected") return "bg-emerald-100 text-emerald-700";
  if (state === "Removed") return "bg-rose-100 text-rose-700";
  if (state === "Locked") return "bg-blue-100 text-blue-700";
  return "bg-slate-100 text-slate-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: WorkspaceRow) {
  return [
    row.workspaceName,
    row.workspaceSlug,
    row.workspaceTypeLabel,
    row.accountClassLabel,
    row.subscriptionStatusLabel,
    row.planName,
    row.eligibilityStatus,
    row.eligibilityLabel,
    row.eligibilityReason,
    row.firstFix,
    row.softWarningTitle,
    row.selectionState,
  ].join(" ").toLowerCase();
}

export function AdminHardBillingGatePilotReadinessPanel() {
  const [review, setReview] = useState<Review | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState("all");
  const [search, setSearch] = useState("");
  const [notes, setNotes] = useState<Record<string, string>>({});
  const [savingId, setSavingId] = useState<string | null>(null);

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

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

  const needle = search.trim().toLowerCase();
  const rows = useMemo(() => {
    return (review?.workspaceRows ?? []).filter((row) => {
      const matchesFilter = filter === "all"
        || row.eligibilityStatus === filter
        || row.selectionState === filter
        || (filter === "selected" && row.selected)
        || (filter === "unselected" && !row.selected)
        || (filter === "needsReview" && ["Check", "Blocked"].includes(row.eligibilityStatus));
      const matchesSearch = !needle || rowText(row).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, filter, needle]);

  async function updatePilot(row: WorkspaceRow, selected: boolean) {
    try {
      setSavingId(row.workspaceId);
      setError(null);
      const data = await apiPost<Review>("/api/admin/hard-billing-gates/pilot-readiness", {
        workspaceId: row.workspaceId,
        selected,
        note: notes[row.workspaceId] ?? "",
      });
      setReview(data);
      setNotes((current) => ({ ...current, [row.workspaceId]: "" }));
    } catch (err: any) {
      setError(err?.message ?? "Failed to update pilot readiness.");
      await loadReview().catch(() => undefined);
    } finally {
      setSavingId(null);
    }
  }

  function exportRows() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-pilot-readiness.csv",
      [
        "Workspace",
        "Slug",
        "Workspace type",
        "Account class",
        "Subscription",
        "Plan",
        "Provider sync",
        "Billing mode",
        "Hard-gate readiness",
        "Eligibility",
        "Eligibility label",
        "Selected",
        "Selected by review",
        "Selected by environment",
        "Selection state",
        "Soft warning severity",
        "Soft warning title",
        "Over limit count",
        "Missing add-on price count",
        "First fix",
        "Pilot effect",
        "Last reviewed",
        "Last reviewed by",
        "Latest note",
      ],
      rows.map((row) => [
        row.workspaceName,
        row.workspaceSlug,
        row.workspaceTypeLabel,
        row.accountClassLabel,
        row.subscriptionStatusLabel,
        row.planName,
        row.providerSyncStatus,
        row.billingMode,
        row.hardGateReadinessStatus,
        row.eligibilityStatus,
        row.eligibilityLabel,
        row.selected ? "Yes" : "No",
        row.selectedByReview ? "Yes" : "No",
        row.selectedByEnvironment ? "Yes" : "No",
        row.selectionState,
        row.softWarningSeverity,
        row.softWarningTitle,
        row.overLimitCount,
        row.missingAddOnPriceCount,
        row.firstFix,
        row.pilotEffect,
        row.lastReviewedAt ?? "",
        row.lastReviewedBy ?? "",
        row.latestNote,
      ]),
    );
  }

  function exportEvents() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-pilot-readiness-history.csv",
      ["Workspace", "Selected", "Readiness", "Reviewed at", "Reviewed by", "Note", "Summary", "Pilot effect"],
      (review?.recentEvents ?? []).map((event) => [
        event.workspaceName,
        event.selected ? "Selected" : "Removed",
        event.readinessStatus,
        event.reviewedAt ?? "",
        event.reviewedBy,
        event.note,
        event.summary,
        event.pilotEffect,
      ]),
    );
  }

  if (!loaded) {
    return <div className="rounded-2xl border border-slate-200 bg-white p-5 text-sm text-slate-600 shadow-sm">Loading hard billing gate pilot readiness…</div>;
  }

  if (!review) {
    return <div className="rounded-2xl border border-rose-200 bg-rose-50 p-5 text-sm text-rose-700">{error ?? "Hard billing gate pilot readiness could not be loaded."}</div>;
  }

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

  return (
    <section className="space-y-4 rounded-2xl border border-slate-200 bg-white p-5 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">v452 readiness</p>
          <h2 className="text-xl font-semibold text-slate-950">Soft-to-hard billing gate pilot readiness</h2>
          <p className="mt-1 max-w-4xl text-sm text-slate-600">
            Select a small review-only pilot allowlist before hard billing gates are ever activated. This panel records Super Admin evidence only. It does not block access, mutate subscriptions, collect payment, or change broker, portal, or load-board rules.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <span className={`rounded-full px-3 py-1 text-xs font-semibold ${statusClasses(summary.overallStatus)}`}>{summary.overallStatus}</span>
          <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">{summary.selectedReadyCount} selected ready</span>
          <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">{summary.readyCandidateCount} candidates</span>
        </div>
      </div>

      {error ? <div className="rounded-xl 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-4">
        <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">Pilot selection</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.selectedPilotCount}</p>
          <p className="text-xs text-slate-500">{summary.selectedNeedsReviewCount} selected rows still need review</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">Candidate coverage</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.readyCandidateCount}</p>
          <p className="text-xs text-slate-500">{summary.checkCandidateCount} check / {summary.blockedCandidateCount} blocked</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">Recording switch</p>
          <p className="mt-2 text-lg font-semibold text-slate-950">{env.pilotReadinessEnabled ? "On" : "Locked"}</p>
          <p className="text-xs text-slate-500">Review-only is {env.pilotReviewOnly ? "on" : "off"}</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">Guardrail posture</p>
        <p className="mt-1">
          Hard gates {env.hardBillingGatesEnabled ? "on" : "off"}, payment collection {env.paymentCollectionEnabled ? "on" : "off"}, billing status mutation {env.billingStatusMutationEnabled ? "on" : "off"}, customer portal activation {env.customerPortalEnabled ? "on" : "off"}. Environment allowlist entries: {env.envAllowlist.length || 0}.
        </p>
      </div>

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
        {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>
          </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="all">All workspaces</option>
            <option value="Ready">Ready candidates</option>
            <option value="Check">Check</option>
            <option value="Blocked">Blocked</option>
            <option value="Locked">Locked</option>
            <option value="selected">Selected</option>
            <option value="unselected">Unselected</option>
            <option value="needsReview">Needs review</option>
          </select>
          <input
            className="min-w-[260px] rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm"
            placeholder="Search workspace, plan, warning, 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={exportRows}>Export pilot rows</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={exportEvents}>Export 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">Eligibility</th>
              <th className="px-4 py-3">Selection</th>
              <th className="px-4 py-3">Billing state</th>
              <th className="px-4 py-3">First fix</th>
              <th className="px-4 py-3">Pilot note</th>
              <th className="px-4 py-3">Action</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>
                </td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2 py-1 text-[11px] font-semibold ${statusClasses(row.eligibilityStatus)}`}>{row.eligibilityStatus}</span>
                  <p className="mt-2 text-xs font-medium text-slate-700">{row.eligibilityLabel}</p>
                  <p className="mt-1 text-xs text-slate-500">{row.eligibilityReason}</p>
                </td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2 py-1 text-[11px] font-semibold ${selectionClasses(row.selectionState)}`}>{row.selectionState}</span>
                  <p className="mt-2 text-xs text-slate-500">Review: {row.selectedByReview ? "yes" : "no"} · Env: {row.selectedByEnvironment ? "yes" : "no"}</p>
                  <p className="mt-1 text-xs text-slate-500">Last: {dateTime(row.lastReviewedAt)}</p>
                </td>
                <td className="px-4 py-3 text-xs text-slate-600">
                  <p className="font-semibold text-slate-800">{row.subscriptionStatusLabel}</p>
                  <p>{row.planName}</p>
                  <p>Provider: {row.providerSyncStatus}</p>
                  <p>Warning: {row.softWarningSeverity} · {row.softWarningCount}</p>
                  <p>Limits: {row.overLimitCount} over / {row.missingAddOnPriceCount} price gaps</p>
                </td>
                <td className="px-4 py-3 text-xs text-slate-600">{row.firstFix}</td>
                <td className="px-4 py-3">
                  <textarea
                    className="min-h-[76px] w-64 rounded-xl border border-slate-300 px-3 py-2 text-xs"
                    placeholder="Optional Super Admin pilot note"
                    value={notes[row.workspaceId] ?? ""}
                    onChange={(event) => setNotes((current) => ({ ...current, [row.workspaceId]: event.target.value }))}
                  />
                  {row.latestNote ? <p className="mt-1 text-xs text-slate-500">Latest: {row.latestNote}</p> : null}
                </td>
                <td className="px-4 py-3">
                  <div className="flex flex-col gap-2">
                    <button
                      className="rounded-xl bg-slate-950 px-3 py-2 text-xs font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300"
                      disabled={!env.pilotReadinessEnabled || row.eligibilityStatus !== "Ready" || savingId === row.workspaceId}
                      onClick={() => updatePilot(row, true)}
                    >
                      {savingId === row.workspaceId ? "Saving…" : "Select for pilot"}
                    </button>
                    <button
                      className="rounded-xl border border-slate-300 px-3 py-2 text-xs font-semibold text-slate-700 disabled:cursor-not-allowed disabled:opacity-50"
                      disabled={!env.pilotReadinessEnabled || savingId === row.workspaceId}
                      onClick={() => updatePilot(row, false)}
                    >
                      Remove
                    </button>
                    <p className="max-w-44 text-[11px] text-slate-500">{row.pilotEffect}</p>
                  </div>
                </td>
              </tr>
            ))}
            {!rows.length ? (
              <tr>
                <td className="px-4 py-6 text-center text-sm text-slate-500" colSpan={7}>No pilot rows match this filter.</td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </div>

      <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
        <h3 className="text-sm font-semibold text-slate-950">Recent pilot readiness evidence</h3>
        <div className="mt-3 grid gap-2 md:grid-cols-2 xl:grid-cols-3">
          {(review.recentEvents ?? []).slice(0, 6).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.workspaceName || "Workspace"}</p>
              <p>{event.selected ? "Selected" : "Removed"} · {event.readinessStatus}</p>
              <p>{dateTime(event.reviewedAt)} by {event.reviewedBy}</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 pilot readiness history has been recorded yet.</p> : null}
        </div>
      </div>
    </section>
  );
}
