"use client";

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

type ReadinessStatus = "Ready" | "Check" | "Blocked" | "Locked";
type ApprovalState = "Approved" | "Not approved" | "Revoked" | "Needs review" | "Locked";

type ReadinessSwitch = {
  key: string;
  label: string;
  status: ReadinessStatus;
  canApprove: boolean;
  detail: string;
  firstFix: string;
  activationEffect: string;
  approved: boolean;
  approvalStatus: ApprovalState;
  lastReviewedAt: string | null;
  lastReviewedBy: string | null;
  note: string;
};

type ReadinessEvent = {
  id: string;
  switchKey: string;
  label: string;
  approved: boolean;
  revoked: boolean;
  note: string;
  reviewedAt: string;
  reviewedBy: string;
  readinessStatus: string;
  summary: string;
};

type Review = {
  summary: {
    readinessStatus: ReadinessStatus;
    requiredSwitches: number;
    approvedSwitches: number;
    missingApprovals: number;
    blockedSwitches: number;
    checkSwitches: number;
    allApproved: boolean;
    canConsiderActivationLater: boolean;
    firstFix: string;
  };
  environment: {
    stripeMode: string;
    readinessSwitchEnabled: boolean;
    paymentCollectionReviewOnly: boolean;
    billingActivationReviewOnly: boolean;
    paymentCollectionEnabled: boolean;
    hardBillingGatesEnabled: boolean;
    billingStatusMutationEnabled: boolean;
    customerPortalEnabled: boolean;
    trialToPaidReviewOnly: boolean;
    subscriptionSyncReviewOnly: boolean;
  };
  evidence: {
    controlledCheckoutUrlReturns: number;
    controlledPortalUrlReturns: number;
    verifiedProviderSyncMutations: number;
    trialToPaidCheckpoints: number;
    paymentCollectionReadinessEvents: number;
    latestPaymentCollectionReadinessAt: string | null;
  };
  switches: ReadinessSwitch[];
  recentEvents: ReadinessEvent[];
  guardrails: {
    readinessOnly: boolean;
    auditEvidenceOnly: boolean;
    paymentCollectionActive: boolean;
    liveCheckoutActivation: boolean;
    customerPortalActivation: boolean;
    webhookSubscriptionMutationActive: boolean;
    trialToPaidConversionActive: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

function statusClasses(status: ReadinessStatus) {
  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 approvalClasses(status: ApprovalState) {
  if (status === "Approved") return "bg-emerald-100 text-emerald-700";
  if (status === "Revoked") return "bg-rose-100 text-rose-700";
  if (status === "Locked") return "bg-blue-100 text-blue-700";
  if (status === "Needs review") return "bg-amber-100 text-amber-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 switchText(item: ReadinessSwitch) {
  return [item.key, item.label, item.status, item.approvalStatus, item.detail, item.firstFix, item.activationEffect, item.note].join(" ").toLowerCase();
}

export function AdminStripePaymentCollectionActivationReadinessPanel() {
  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 [savingKey, setSavingKey] = useState<string | null>(null);

  async function loadReview() {
    const data = await apiGet<Review>("/api/admin/stripe-payment-collection/activation-readiness");
    setReview(data);
  }

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

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

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

  const needle = search.trim().toLowerCase();
  const rows = useMemo(() => {
    return (review?.switches ?? []).filter((item) => {
      const matchesFilter = filter === "all"
        || item.status === filter
        || item.approvalStatus === filter
        || (filter === "approved" && item.approved)
        || (filter === "missing" && !item.approved)
        || (filter === "needsReview" && (item.status === "Check" || item.status === "Blocked"));
      const matchesSearch = !needle || switchText(item).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, filter, needle]);

  async function updateSwitch(item: ReadinessSwitch, approved: boolean) {
    try {
      setSavingKey(item.key);
      setError(null);
      const data = await apiPost<Review>("/api/admin/stripe-payment-collection/activation-readiness", {
        key: item.key,
        approved,
        note: notes[item.key] ?? "",
      });
      setReview(data);
      setNotes((current) => ({ ...current, [item.key]: "" }));
    } catch (err: any) {
      setError(err?.message ?? "Failed to update readiness switch.");
      await loadReview().catch(() => undefined);
    } finally {
      setSavingKey(null);
    }
  }

  function exportSwitches() {
    downloadCsv(
      "dispatchspot-payment-collection-activation-readiness-switches.csv",
      ["Key", "Label", "Readiness", "Approval", "Can approve", "Approved", "Last reviewed", "Last reviewed by", "Detail", "First fix", "Activation effect", "Note"],
      (review?.switches ?? []).map((item) => [
        item.key,
        item.label,
        item.status,
        item.approvalStatus,
        item.canApprove ? "Yes" : "No",
        item.approved ? "Yes" : "No",
        dateTime(item.lastReviewedAt),
        item.lastReviewedBy ?? "",
        item.detail,
        item.firstFix,
        item.activationEffect,
        item.note,
      ]),
    );
  }

  function exportHistory() {
    downloadCsv(
      "dispatchspot-payment-collection-activation-readiness-history.csv",
      ["Switch", "Label", "Approved", "Revoked", "Readiness", "Reviewed at", "Reviewed by", "Summary", "Note"],
      (review?.recentEvents ?? []).map((event) => [
        event.switchKey,
        event.label,
        event.approved ? "Yes" : "No",
        event.revoked ? "Yes" : "No",
        event.readinessStatus,
        dateTime(event.reviewedAt),
        event.reviewedBy,
        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 payment collection activation readiness…</p>
      </section>
    );
  }

  if (error && !review) {
    return (
      <section className="rounded-3xl border border-rose-200 bg-rose-50 p-6 shadow-sm">
        <h2 className="text-lg font-semibold text-rose-900">Payment collection activation readiness could not load</h2>
        <p className="mt-2 text-sm text-rose-700">{error}</p>
      </section>
    );
  }

  if (!review) return null;

  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>
          <div className="flex flex-wrap items-center gap-2">
            <h2 className="text-xl font-semibold text-slate-900">Payment collection activation readiness switch</h2>
            <span className={`rounded-full px-3 py-1 text-xs font-semibold ${statusClasses(review.summary.readinessStatus)}`}>{review.summary.readinessStatus}</span>
          </div>
          <p className="mt-2 max-w-4xl text-sm leading-6 text-slate-600">
            Final Super Admin review switches for future payment collection activation. This panel records evidence only. It does not turn on live billing, open live checkout, change subscription status, or block any workspace.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <button type="button" onClick={exportSwitches} className="rounded-xl bg-slate-900 px-4 py-2 text-xs font-semibold text-white">Export switches</button>
          <button type="button" onClick={exportHistory} className="rounded-xl border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700">Export history</button>
        </div>
      </div>

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

      <div className="grid gap-3 md:grid-cols-4 xl:grid-cols-8">
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Approved</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.approvedSwitches}/{review.summary.requiredSwitches}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Missing</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.missingApprovals}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Blocked</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.blockedSwitches}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Review flag</div><div className="mt-1 text-sm font-semibold text-slate-900">{review.environment.readinessSwitchEnabled ? "On" : "Locked"}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Checkout URLs</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.evidence.controlledCheckoutUrlReturns}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Portal URLs</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.evidence.controlledPortalUrlReturns}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Sync evidence</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.evidence.verifiedProviderSyncMutations}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Trial checkpoints</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.evidence.trialToPaidCheckpoints}</div></div>
      </div>

      <div className="rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm leading-6 text-blue-900">
        <span className="font-semibold">Review posture:</span> {review.summary.firstFix}
        <div className="mt-1 text-blue-800">
          Stripe mode is {review.environment.stripeMode}. Payment collection is {review.environment.paymentCollectionEnabled ? "on" : "off"}. Hard billing gates are {review.environment.hardBillingGatesEnabled ? "on" : "off"}. Trial conversion and subscription sync review-only settings are {review.environment.trialToPaidReviewOnly && review.environment.subscriptionSyncReviewOnly ? "on" : "not clean"}.
        </div>
      </div>

      <div className="grid gap-3 md:grid-cols-4">
        <label className="text-sm font-medium text-slate-700">Switch filter
          <select value={filter} onChange={(event) => setFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            <option value="all">All switches</option>
            <option value="approved">Approved</option>
            <option value="missing">Missing approval</option>
            <option value="needsReview">Needs review</option>
            <option value="Ready">Ready</option>
            <option value="Check">Check</option>
            <option value="Blocked">Blocked</option>
            <option value="Locked">Locked</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700 md:col-span-3">Search
          <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Switch, evidence, first fix, note..." className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm" />
        </label>
      </div>

      <div className="grid gap-4 xl:grid-cols-3">
        <div className="space-y-3 xl:col-span-2">
          <div className="flex items-center justify-between gap-3">
            <h3 className="text-sm font-semibold text-slate-900">Readiness switches</h3>
            <div className="text-sm text-slate-500">Filtered switches: {rows.length}</div>
          </div>
          {rows.length === 0 ? <div className="rounded-xl bg-slate-50 p-4 text-sm text-slate-600">No switches match the filters.</div> : rows.map((item) => (
            <div key={item.key} className="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-sm">
              <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                <div>
                  <div className="font-semibold text-slate-900">{item.label}</div>
                  <p className="mt-2 leading-6 text-slate-600">{item.detail}</p>
                </div>
                <div className="flex flex-wrap items-center gap-2 md:justify-end">
                  <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(item.status)}`}>{item.status}</span>
                  <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${approvalClasses(item.approvalStatus)}`}>{item.approvalStatus}</span>
                </div>
              </div>
              <div className="mt-3 grid gap-3 md:grid-cols-2">
                <div className="rounded-xl bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">First fix:</span> {item.firstFix}</div>
                <div className="rounded-xl bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">Effect:</span> {item.activationEffect}</div>
              </div>
              <div className="mt-3 grid gap-3 md:grid-cols-[1fr_auto_auto] md:items-end">
                <label className="text-xs font-medium text-slate-700">Review note
                  <input value={notes[item.key] ?? ""} onChange={(event) => setNotes((current) => ({ ...current, [item.key]: event.target.value }))} placeholder={item.note || "Optional readiness note"} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm" />
                </label>
                <button
                  type="button"
                  disabled={!review.environment.readinessSwitchEnabled || !item.canApprove || savingKey === item.key}
                  onClick={() => updateSwitch(item, true)}
                  className="rounded-xl bg-blue-700 px-4 py-2 text-xs font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300"
                >
                  {savingKey === item.key ? "Saving..." : item.approved ? "Re-approve" : "Approve"}
                </button>
                <button
                  type="button"
                  disabled={!review.environment.readinessSwitchEnabled || savingKey === item.key || (!item.approved && item.approvalStatus !== "Approved")}
                  onClick={() => updateSwitch(item, false)}
                  className="rounded-xl border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700 disabled:cursor-not-allowed disabled:text-slate-300"
                >
                  Revoke
                </button>
              </div>
              <div className="mt-3 text-xs text-slate-500">Last reviewed: {dateTime(item.lastReviewedAt)} {item.lastReviewedBy ? `by ${item.lastReviewedBy}` : ""}</div>
            </div>
          ))}
        </div>

        <div className="space-y-3">
          <h3 className="text-sm font-semibold text-slate-900">Recent readiness history</h3>
          {review.recentEvents.length === 0 ? <div className="rounded-xl bg-slate-50 p-4 text-sm text-slate-600">No payment collection readiness switch history yet.</div> : review.recentEvents.map((event) => (
            <div key={event.id} className="rounded-2xl border border-slate-100 bg-white p-4 text-sm">
              <div className="font-semibold text-slate-900">{event.label || event.switchKey}</div>
              <div className="mt-1 text-xs text-slate-500">{dateTime(event.reviewedAt)} · {event.reviewedBy}</div>
              <div className="mt-3 flex flex-wrap gap-2">
                <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${event.approved ? "bg-emerald-100 text-emerald-700" : "bg-rose-100 text-rose-700"}`}>{event.approved ? "Approved" : "Revoked"}</span>
                <span className="rounded-full bg-slate-100 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-slate-700">{event.readinessStatus}</span>
              </div>
              <p className="mt-3 text-xs leading-5 text-slate-600">{event.summary}</p>
              {event.note ? <div className="mt-3 rounded-xl bg-slate-50 p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">Note:</span> {event.note}</div> : null}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
