"use client";

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

type ActivationStatus = "Ready" | "Check" | "Blocked" | "Locked";

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

type ImpactRow = {
  workspaceId: string;
  workspaceName: string;
  workspaceSlug: string;
  workspaceTypeLabel: string;
  accountClassLabel: string;
  selected: boolean;
  selectionState: string;
  eligibilityStatus: string;
  eligibilityLabel: string;
  subscriptionStatus: string;
  subscriptionStatusLabel: string;
  planName: string;
  providerSyncStatus: string;
  softWarningSeverity: string;
  softWarningTitle: string;
  overLimitCount: number;
  missingAddOnPriceCount: number;
  hardGatePolicyMode: string;
  hardGateActiveForWorkspace: boolean;
  workspaceInPilot: boolean;
  impactStatus: string;
  accessEffect: string;
  firstFix: string;
};

type ReviewEvent = {
  id: string;
  reviewedAt: string | null;
  reviewedBy: string;
  activationEnabled: boolean;
  reviewOnly: boolean;
  affectedWorkspaceCount: number;
  blockedImpactCount: number;
  note: string;
  summary: string;
};

type Review = {
  summary: {
    overallStatus: ActivationStatus;
    controlledActivationActive: boolean;
    selectedPilotCount: number;
    selectedReadyCount: number;
    selectedNeedsReviewCount: number;
    activeWorkspaceCount: number;
    blockedImpactCount: number;
    softOnlyCount: number;
    canActivatePilot: boolean;
    firstFix: string;
  };
  environment: {
    controlledActivationEnabled: boolean;
    controlledActivationReviewOnly: boolean;
    broadHardBillingGatesEnabled: boolean;
    paymentCollectionEnabled: boolean;
    billingStatusMutationEnabled: boolean;
    customerPortalEnabled: boolean;
    pilotRollbackActive: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
    envIdentifiers: string[];
  };
  checks: CheckRow[];
  impactRows: ImpactRow[];
  pilotImpactRows: ImpactRow[];
  recentEvents: ReviewEvent[];
  guardrails: {
    controlledPilotOnly: boolean;
    paymentCollectionActive: boolean;
    billingStatusMutationActive: boolean;
    broadHardBillingGatesActive: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

function statusClasses(status: ActivationStatus | string) {
  if (status === "Ready" || status === "No current block") return "bg-emerald-100 text-emerald-700";
  if (status === "Blocked" || status === "Billing hold" || status === "Limit create block" || status === "Unsafe selection") return "bg-rose-100 text-rose-700";
  if (status === "Locked" || status === "Not in pilot") 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: ImpactRow) {
  return [
    row.workspaceName,
    row.workspaceSlug,
    row.workspaceTypeLabel,
    row.accountClassLabel,
    row.selectionState,
    row.eligibilityStatus,
    row.subscriptionStatusLabel,
    row.planName,
    row.hardGatePolicyMode,
    row.impactStatus,
    row.accessEffect,
    row.firstFix,
  ].join(" ").toLowerCase();
}

export function AdminHardBillingGateControlledActivationPanel() {
  const [review, setReview] = useState<Review | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState("pilot");
  const [search, setSearch] = useState("");
  const [note, setNote] = useState("");
  const [saving, setSaving] = useState(false);

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

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

  const needle = search.trim().toLowerCase();
  const rows = useMemo(() => {
    const base = filter === "pilot" ? (review?.pilotImpactRows ?? []) : (review?.impactRows ?? []);
    return base.filter((row) => {
      const matchesFilter = filter === "all" || filter === "pilot"
        || (filter === "active" && row.hardGateActiveForWorkspace)
        || (filter === "selected" && row.selected)
        || row.impactStatus === filter
        || row.eligibilityStatus === filter;
      const matchesSearch = !needle || rowText(row).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, filter, needle]);

  async function recordReview() {
    try {
      setSaving(true);
      setError(null);
      const data = await apiPost<Review>("/api/admin/hard-billing-gates/controlled-activation", { note });
      setReview(data);
      setNote("");
    } catch (err: any) {
      setError(err?.message ?? "Failed to record controlled activation review.");
      await loadReview().catch(() => undefined);
    } finally {
      setSaving(false);
    }
  }

  function exportRows() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-controlled-activation-impact.csv",
      ["Workspace", "Slug", "Selected", "Policy mode", "Active", "Impact", "Eligibility", "Subscription", "Plan", "Provider sync", "Over limits", "Access effect", "First fix"],
      (review?.impactRows ?? []).map((row) => [
        row.workspaceName,
        row.workspaceSlug,
        row.selected ? "Yes" : "No",
        row.hardGatePolicyMode,
        row.hardGateActiveForWorkspace ? "Yes" : "No",
        row.impactStatus,
        `${row.eligibilityStatus} - ${row.eligibilityLabel}`,
        row.subscriptionStatusLabel,
        row.planName,
        row.providerSyncStatus,
        row.overLimitCount,
        row.accessEffect,
        row.firstFix,
      ]),
    );
  }

  function exportHistory() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-controlled-activation-history.csv",
      ["Reviewed at", "Reviewed by", "Activation enabled", "Review only", "Affected workspaces", "Blocked impact", "Summary", "Note"],
      (review?.recentEvents ?? []).map((event) => [
        dateTime(event.reviewedAt),
        event.reviewedBy,
        event.activationEnabled ? "Yes" : "No",
        event.reviewOnly ? "Yes" : "No",
        event.affectedWorkspaceCount,
        event.blockedImpactCount,
        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 controlled hard billing gate activation 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 ?? "Controlled hard billing gate activation 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">v453 controlled activation</p>
          <h2 className="mt-1 text-xl font-semibold text-slate-950">Hard billing gate controlled activation</h2>
          <p className="mt-2 max-w-3xl text-sm text-slate-600">
            Pilot-only activation review for hard billing gates. This does not turn on payment collection, billing status mutation, broker distribution limits, owned portal rules, or 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-5">
        <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">Controlled active</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.controlledActivationActive ? "Yes" : "No"}</p>
          <p className="text-xs text-slate-500">{summary.activeWorkspaceCount} active pilot workspace rows</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">Pilot selection</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.selectedReadyCount}</p>
          <p className="text-xs text-slate-500">{summary.selectedNeedsReviewCount} selected rows 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">Possible blocks</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.blockedImpactCount}</p>
          <p className="text-xs text-slate-500">Controlled pilot only</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">Activation flags</p>
          <p className="mt-2 text-lg font-semibold text-slate-950">{env.controlledActivationEnabled ? "On" : "Off"}</p>
          <p className="text-xs text-slate-500">Review-only is {env.controlledActivationReviewOnly ? "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">
          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"}. Pilot identifiers: {env.envIdentifiers.length || 0}. Rollback stop {env.pilotRollbackActive ? "on" : "off"}.
        </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>
            <p className="mt-2 text-[11px] text-slate-500">{item.activationEffect}</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="pilot">Pilot impact rows</option>
            <option value="all">All workspaces</option>
            <option value="active">Hard gate active</option>
            <option value="selected">Selected</option>
            <option value="Billing hold">Billing hold</option>
            <option value="Limit create block">Limit create block</option>
            <option value="No current block">No current block</option>
            <option value="Check">Needs review</option>
            <option value="Blocked">Blocked</option>
          </select>
          <input
            className="min-w-[260px] rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm"
            placeholder="Search workspace, policy, impact, 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 impact 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={exportHistory}>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">Policy</th>
              <th className="px-4 py-3">Impact</th>
              <th className="px-4 py-3">Billing state</th>
              <th className="px-4 py-3">Access effect</th>
              <th className="px-4 py-3">First fix</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 text-xs text-slate-600">
                  <p className="font-semibold text-slate-800">{row.hardGatePolicyMode}</p>
                  <p>Active: {row.hardGateActiveForWorkspace ? "yes" : "no"}</p>
                  <p>Selected: {row.selected ? "yes" : "no"}</p>
                  <p>In pilot: {row.workspaceInPilot ? "yes" : "no"}</p>
                </td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2 py-1 text-[11px] font-semibold ${statusClasses(row.impactStatus)}`}>{row.impactStatus}</span>
                  <p className="mt-2 text-xs text-slate-500">{row.eligibilityStatus} · {row.eligibilityLabel}</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}</p>
                  <p>Limits: {row.overLimitCount} over / {row.missingAddOnPriceCount} price gaps</p>
                </td>
                <td className="px-4 py-3 text-xs text-slate-600">{row.accessEffect}</td>
                <td className="px-4 py-3 text-xs text-slate-600">{row.firstFix}</td>
              </tr>
            ))}
            {!rows.length ? (
              <tr>
                <td className="px-4 py-6 text-center text-sm text-slate-500" colSpan={6}>No controlled activation 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 Super Admin review</h3>
          <p className="mt-1 text-xs text-slate-500">Recording review creates audit evidence only. Runtime behavior still depends on explicit environment flags and pilot identifiers.</p>
          <textarea
            className="mt-3 min-h-[84px] w-full rounded-xl border border-slate-300 px-3 py-2 text-sm"
            placeholder="Optional review note or rollback comment"
            value={note}
            onChange={(event) => setNote(event.target.value)}
          />
          <button
            className="mt-3 rounded-xl bg-slate-950 px-4 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300"
            disabled={saving}
            onClick={recordReview}
          >
            {saving ? "Recording…" : "Record controlled activation review"}
          </button>
        </div>
        <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
          <h3 className="text-sm font-semibold text-slate-950">Recent controlled activation evidence</h3>
          <div className="mt-3 grid gap-2 md:grid-cols-2">
            {(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.summary}</p>
                <p>{dateTime(event.reviewedAt)} by {event.reviewedBy}</p>
                <p>Enabled: {event.activationEnabled ? "yes" : "no"} · Review-only: {event.reviewOnly ? "yes" : "no"}</p>
                <p>Affected: {event.affectedWorkspaceCount} · Possible blocks: {event.blockedImpactCount}</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 controlled activation history has been recorded yet.</p> : null}
          </div>
        </div>
      </div>
    </section>
  );
}
