"use client";

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

type PilotCloseoutStatus = "Ready" | "Check" | "Blocked" | "Locked";
type PilotCloseoutRowStatus = "Ready to close" | "Support watch" | "Escalated" | "Rolled back" | "Standby" | "Locked";

type CloseoutCheckRow = {
  key: string;
  label: string;
  status: PilotCloseoutStatus;
  detail: string;
  firstFix: string;
  closeoutEffect: string;
};

type CloseoutRow = {
  workspaceId: string;
  workspaceName: string;
  workspaceSlug: string;
  workspaceTypeLabel: string;
  accountClassLabel: string;
  selected: boolean;
  workspaceInPilot: boolean;
  hardGatePolicyMode: string;
  hardGateActiveForWorkspace: boolean;
  impactStatus: string;
  safetyStatus: string;
  subscriptionStatusLabel: string;
  planName: string;
  providerSyncStatus: string;
  closeoutStatus: PilotCloseoutRowStatus;
  closeoutNextStep: string;
  operatorSupportCopy: string;
  superAdminCloseoutNote: string;
};

type SupportCopyBlock = {
  key: string;
  label: string;
  audience: string;
  whenToUse: string;
  copy: string;
};

type EvidenceEvent = {
  id: string;
  action: string;
  recordedAt: string | null;
  recordedBy: string;
  summary: string;
  note: string;
  closeoutStatus: string;
  activePilotWorkspaceCount: number;
  watchCount: number;
  escalationCount: number;
  rollbackActive: boolean;
};

type CloseoutPacketItem = {
  section: string;
  detail: string;
  exportInstruction: string;
};

type Review = {
  summary: {
    overallStatus: PilotCloseoutStatus;
    monitoredWorkspaceCount: number;
    activePilotWorkspaceCount: number;
    readyToCloseCount: number;
    supportWatchCount: number;
    escalationCount: number;
    rolledBackCount: number;
    pilotSelectionEvidenceCount: number;
    controlledEvidenceCount: number;
    safetyEvidenceCount: number;
    closeoutReviewCount: number;
    supportCopyCount: number;
    canRecordCloseout: boolean;
    evidenceExportRequired: boolean;
    firstFix: string;
  };
  environment: {
    closeoutReviewEnabled: boolean;
    supportCopyEnabled: boolean;
    supportContactLabel: string;
    evidenceExportRequired: boolean;
    rollbackActive: boolean;
    broadHardBillingGatesEnabled: boolean;
    paymentCollectionEnabled: boolean;
    billingStatusMutationEnabled: boolean;
    customerPortalEnabled: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
  checks: CloseoutCheckRow[];
  closeoutRows: CloseoutRow[];
  supportCopyBlocks: SupportCopyBlock[];
  recentEvents: EvidenceEvent[];
  closeoutPacket: CloseoutPacketItem[];
};

function statusClasses(status: PilotCloseoutStatus | PilotCloseoutRowStatus | string) {
  if (status === "Ready" || status === "Ready to close") return "bg-emerald-100 text-emerald-700";
  if (status === "Blocked" || status === "Escalated") return "bg-rose-100 text-rose-700";
  if (status === "Locked" || status === "Standby" || status === "Rolled back") 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: CloseoutRow) {
  return [
    row.workspaceName,
    row.workspaceSlug,
    row.workspaceTypeLabel,
    row.accountClassLabel,
    row.hardGatePolicyMode,
    row.impactStatus,
    row.safetyStatus,
    row.closeoutStatus,
    row.closeoutNextStep,
    row.operatorSupportCopy,
    row.superAdminCloseoutNote,
    row.subscriptionStatusLabel,
    row.planName,
  ].join(" ").toLowerCase();
}

export function AdminHardBillingGatePilotCloseoutPanel() {
  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 [note, setNote] = useState("");
  const [saving, setSaving] = useState(false);

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

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

  const needle = search.trim().toLowerCase();
  const rows = useMemo(() => {
    return (review?.closeoutRows ?? []).filter((row) => {
      const matchesFilter = filter === "all"
        || row.closeoutStatus === filter
        || row.impactStatus === filter
        || row.safetyStatus === filter
        || (filter === "active" && row.hardGateActiveForWorkspace);
      const matchesSearch = !needle || rowText(row).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, filter, needle]);

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

  function exportRows() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-pilot-closeout-rows.csv",
      ["Workspace", "Slug", "Closeout", "Safety", "Impact", "Policy", "Hard gate active", "Subscription", "Plan", "Provider sync", "Next step", "Support copy", "Super Admin note"],
      (review?.closeoutRows ?? []).map((row) => [
        row.workspaceName,
        row.workspaceSlug,
        row.closeoutStatus,
        row.safetyStatus,
        row.impactStatus,
        row.hardGatePolicyMode,
        row.hardGateActiveForWorkspace ? "Yes" : "No",
        row.subscriptionStatusLabel,
        row.planName,
        row.providerSyncStatus,
        row.closeoutNextStep,
        row.operatorSupportCopy,
        row.superAdminCloseoutNote,
      ]),
    );
  }

  function exportSupportCopy() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-pilot-support-copy.csv",
      ["Key", "Label", "Audience", "When to use", "Copy"],
      (review?.supportCopyBlocks ?? []).map((item) => [item.key, item.label, item.audience, item.whenToUse, item.copy]),
    );
  }

  function exportEvidenceHistory() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-pilot-closeout-history.csv",
      ["Recorded at", "Recorded by", "Action", "Closeout status", "Rollback active", "Active pilot workspaces", "Watch", "Escalations", "Summary", "Note"],
      (review?.recentEvents ?? []).map((event) => [
        dateTime(event.recordedAt),
        event.recordedBy,
        event.action,
        event.closeoutStatus,
        event.rollbackActive ? "Yes" : "No",
        event.activePilotWorkspaceCount,
        event.watchCount,
        event.escalationCount,
        event.summary,
        event.note,
      ]),
    );
  }

  function exportCloseoutPacket() {
    downloadCsv(
      "dispatchspot-hard-billing-gate-pilot-closeout-packet.csv",
      ["Section", "Detail", "Export instruction"],
      (review?.closeoutPacket ?? []).map((item) => [item.section, item.detail, item.exportInstruction]),
    );
  }

  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 pilot closeout…</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 pilot closeout 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">v455 closeout and support copy</p>
          <h2 className="mt-1 text-xl font-semibold text-slate-950">Hard-gate pilot evidence closeout</h2>
          <p className="mt-2 max-w-3xl text-sm text-slate-600">
            Super Admin can close out the controlled hard-gate pilot evidence, export the support copy, and keep a clean packet before any later payment collection, broad hard-gate, broker, portal, or load-board change is considered.
          </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">Closeout reviews</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.closeoutReviewCount}</p>
          <p className="text-xs text-slate-500">Recording {summary.canRecordCloseout ? "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">Active pilot</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.activePilotWorkspaceCount}</p>
          <p className="text-xs text-slate-500">{summary.monitoredWorkspaceCount} monitored 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">Ready</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.readyToCloseCount}</p>
          <p className="text-xs text-slate-500">ready to close</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">Support watch</p>
          <p className="mt-2 text-2xl font-semibold text-slate-950">{summary.supportWatchCount}</p>
          <p className="text-xs text-slate-500">{summary.escalationCount} escalated</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.pilotSelectionEvidenceCount + summary.controlledEvidenceCount + summary.safetyEvidenceCount}</p>
          <p className="text-xs text-slate-500">pilot + controlled + safety</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">Closeout posture</p>
        <p className="mt-1">
          Support copy {env.supportCopyEnabled ? "enabled" : "locked"}; support contact label: {env.supportContactLabel}. 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.closeoutEffect}</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">Closeout packet</h3>
            <p className="mt-1 text-xs text-slate-500">Keep these packet sections with the pilot record before expanding any hard-gate scope.</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={exportCloseoutPacket}>Export packet checklist</button>
        </div>
        <div className="mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          {review.closeoutPacket.map((item) => (
            <div key={item.section} className="rounded-xl border border-slate-200 bg-white p-3 text-xs text-slate-600">
              <p className="font-semibold text-slate-900">{item.section}</p>
              <p className="mt-2">{item.detail}</p>
              <p className="mt-2 font-medium text-slate-700">{item.exportInstruction}</p>
            </div>
          ))}
        </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">Operator support copy</h3>
            <p className="mt-1 text-xs text-slate-500">Plain-language copy for support operators. It avoids technical setup details and does not change workspace access.</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={exportSupportCopy}>Export support copy</button>
        </div>
        <div className="mt-3 grid gap-3 lg:grid-cols-2">
          {review.supportCopyBlocks.map((item) => (
            <div key={item.key} className="rounded-xl border border-slate-200 bg-white p-4 text-sm">
              <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                <p className="font-semibold text-slate-900">{item.label}</p>
                <span className="rounded-full bg-slate-100 px-2 py-1 text-[11px] font-semibold text-slate-600">{item.audience}</span>
              </div>
              <p className="mt-2 text-xs font-medium text-slate-600">{item.whenToUse}</p>
              <p className="mt-3 rounded-xl bg-slate-50 p-3 text-sm leading-6 text-slate-700">{item.copy}</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="all">All closeout rows</option>
            <option value="active">Hard gate active</option>
            <option value="Ready to close">Ready to close</option>
            <option value="Support watch">Support watch</option>
            <option value="Escalated">Escalated</option>
            <option value="Rolled back">Rolled back</option>
            <option value="Standby">Standby</option>
            <option value="Billing hold">Billing hold</option>
            <option value="Limit create block">Limit create block</option>
          </select>
          <input
            className="min-w-[260px] rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm"
            placeholder="Search workspace, closeout, support copy…"
            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 closeout 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={exportEvidenceHistory}>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">Closeout</th>
              <th className="px-4 py-3">Pilot state</th>
              <th className="px-4 py-3">Support copy</th>
              <th className="px-4 py-3">Next step</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.closeoutStatus)}`}>{row.closeoutStatus}</span>
                  <p className="mt-2 text-xs text-slate-600">{row.superAdminCloseoutNote}</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>Safety: {row.safetyStatus}</p>
                  <p>Impact: {row.impactStatus}</p>
                  <p>{row.subscriptionStatusLabel} · {row.planName}</p>
                </td>
                <td className="px-4 py-3 text-xs leading-5 text-slate-600">{row.operatorSupportCopy}</td>
                <td className="px-4 py-3 text-xs leading-5 text-slate-600">{row.closeoutNextStep}</td>
              </tr>
            ))}
            {!rows.length ? (
              <tr>
                <td className="px-4 py-6 text-center text-sm text-slate-500" colSpan={5}>No pilot closeout 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 closeout evidence</h3>
          <p className="mt-1 text-xs text-slate-500">Recording closeout evidence does not change environment flags, collect payment, 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 closeout 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={saving || !summary.canRecordCloseout}
              onClick={recordCloseout}
            >
              {saving ? "Recording…" : "Record closeout review"}
            </button>
            {!summary.canRecordCloseout ? <p className="self-center text-xs text-slate-500">Closeout recording is locked by environment flag.</p> : null}
          </div>
        </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 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>Rollback: {event.rollbackActive ? "yes" : "no"} · Active: {event.activePilotWorkspaceCount} · Watch: {event.watchCount} · Escalations: {event.escalationCount}</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 closeout evidence has been recorded yet.</p> : null}
          </div>
        </div>
      </div>
    </section>
  );
}
