"use client";

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

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

type CheckpointCheck = {
  key: string;
  label: string;
  status: CheckpointStatus;
  detail: string;
  firstFix: string;
};

type CandidateRow = {
  id: string;
  workspaceName: string;
  workspaceSlug: string;
  adminEmail: string;
  workspaceType: string;
  accountClass: string;
  organizationActive: boolean;
  subscriptionStatus: string;
  planName: string;
  planReadiness: string;
  trialEndsAt: string | null;
  daysRemaining: number | null;
  providerSyncStatus: string;
  billingProviderStatus: string;
  currentPeriodEndsAt: string | null;
  stripeCustomerIdMasked: string;
  stripeSubscriptionIdMasked: string;
  stripeSubscriptionItemIdMasked: string;
  evidenceEventId: string;
  evidenceEventType: string;
  evidenceCreatedAt: string | null;
  checkpointState: string;
  checkpointLabel: string;
  readinessStatus: CheckpointStatus;
  checkpointRecordedAt: string | null;
  firstFix: string;
};

type CheckpointEvent = {
  id: string;
  targetId: string | null;
  workspaceName: string;
  workspaceSlug: string;
  reviewedBy: string;
  summary: string;
  note: string;
  currentStatus: string;
  providerStatus: string;
  evidenceEventId: string;
  createdAt: string;
};

type Review = {
  summary: {
    readinessStatus: CheckpointStatus;
    trialWorkspaces: number;
    readyForCheckpoint: number;
    checkpointRecorded: number;
    missingTrialEnd: number;
    dueWithinSevenDays: number;
    expiredTrials: number;
    paidLikeProviderSignals: number;
    verifiedProviderSyncEvidence: number;
    testMutationAuditEvents: number;
    checkpointEvents: number;
    latestCheckpointAt: string | null;
    firstFix: string;
  };
  environment: {
    stripeMode: string;
    webhookSecretConfigured: boolean;
    webhookIntakeEnabled: boolean;
    webhookSubscriptionSyncEnabled: boolean;
    webhookTestSyncMutationEnabled: boolean;
    checkpointEnabled: boolean;
    paymentCollectionEnabled: boolean;
    customerPortalEnabled: boolean;
    hardBillingGatesEnabled: boolean;
    billingStatusMutationEnabled: boolean;
    subscriptionSyncReviewOnly: boolean;
    trialToPaidReviewOnly: boolean;
  };
  checks: CheckpointCheck[];
  candidateRows: CandidateRow[];
  recentCheckpoints: CheckpointEvent[];
  guardrails: {
    evidenceOnly: boolean;
    checkpointRecordsOnly: boolean;
    workspaceStatusMutationActive: boolean;
    trialConvertedToPaid: boolean;
    paymentCollectionActive: boolean;
    customerPortalActive: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

function statusClasses(status: CheckpointStatus) {
  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 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: CandidateRow) {
  return [row.workspaceName, row.workspaceSlug, row.adminEmail, row.workspaceType, row.accountClass, row.planName, row.providerSyncStatus, row.billingProviderStatus, row.checkpointLabel, row.firstFix].join(" ").toLowerCase();
}

export function AdminStripeTrialToPaidTestCheckpointPanel() {
  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 [postingId, setPostingId] = useState<string | null>(null);

  async function loadReview() {
    const data = await apiGet<Review>("/api/admin/trial-to-paid/test-checkpoint");
    setReview(data);
  }

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

  const needle = search.trim().toLowerCase();
  const rows = useMemo(() => {
    return (review?.candidateRows ?? []).filter((row) => {
      const matchesFilter = filter === "all"
        || row.readinessStatus === filter
        || row.checkpointState === filter
        || (filter === "ready" && row.checkpointState === "ready_for_checkpoint")
        || (filter === "recorded" && row.checkpointState === "checkpoint_recorded")
        || (filter === "needsReview" && row.readinessStatus !== "Ready")
        || (filter === "dueSoon" && row.daysRemaining !== null && row.daysRemaining >= 0 && row.daysRemaining <= 7)
        || (filter === "expired" && row.daysRemaining !== null && row.daysRemaining < 0);
      const matchesSearch = !needle || rowText(row).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, filter, needle]);

  async function recordCheckpoint(row: CandidateRow) {
    try {
      setPostingId(row.id);
      setError(null);
      const data = await apiPost<Review>("/api/admin/trial-to-paid/test-checkpoint", { workspaceSubscriptionId: row.id, note });
      setReview(data);
      setNote("");
    } catch (err: any) {
      setError(err?.message ?? "Failed to record checkpoint.");
      await loadReview().catch(() => undefined);
    } finally {
      setPostingId(null);
    }
  }

  function exportRows() {
    downloadCsv(
      "dispatchspot-trial-to-paid-test-checkpoint.csv",
      ["Workspace", "Slug", "Admin", "Type", "Account class", "Plan", "Trial end", "Days remaining", "Provider sync", "Provider status", "Current period end", "Customer", "Subscription", "Evidence event", "Evidence type", "Checkpoint state", "Readiness", "Checkpoint recorded", "First fix"],
      rows.map((row) => [
        row.workspaceName,
        row.workspaceSlug,
        row.adminEmail,
        row.workspaceType,
        row.accountClass,
        row.planName,
        dateTime(row.trialEndsAt),
        row.daysRemaining ?? "",
        row.providerSyncStatus,
        row.billingProviderStatus,
        dateTime(row.currentPeriodEndsAt),
        row.stripeCustomerIdMasked,
        row.stripeSubscriptionIdMasked,
        row.evidenceEventId,
        row.evidenceEventType,
        row.checkpointLabel,
        row.readinessStatus,
        dateTime(row.checkpointRecordedAt),
        row.firstFix,
      ]),
    );
  }

  function exportCheckpoints() {
    downloadCsv(
      "dispatchspot-trial-to-paid-checkpoint-history.csv",
      ["Recorded", "Workspace", "Slug", "Reviewed by", "Current status", "Provider status", "Evidence event", "Note", "Summary"],
      (review?.recentCheckpoints ?? []).map((event) => [dateTime(event.createdAt), event.workspaceName, event.workspaceSlug, event.reviewedBy, event.currentStatus, event.providerStatus, event.evidenceEventId, event.note, event.summary]),
    );
  }

  if (!loaded) {
    return <section className="rounded-2xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Loading trial-to-paid test checkpoint...</section>;
  }

  if (error && !review) {
    return <section className="rounded-2xl border border-rose-100 bg-rose-50 p-6 text-sm text-rose-700 shadow-sm">{error}</section>;
  }

  if (!review) return null;

  return (
    <section className="space-y-5 rounded-2xl border bg-white p-6 shadow-sm">
      <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Trial-to-paid checkpoint</div>
          <h2 className="mt-1 text-xl font-semibold text-slate-900">Trial-to-paid conversion test checkpoint</h2>
          <p className="mt-1 max-w-4xl text-sm leading-6 text-slate-600">
            Review whether trial workspaces have enough Stripe test evidence for a future conversion. This records Super Admin checkpoint evidence only. It does not change a workspace from trial to paid, collect payment, open the customer portal, or change access.
          </p>
        </div>
        <span className={`rounded-full px-3 py-1 text-xs font-semibold ${statusClasses(review.summary.readinessStatus)}`}>{review.summary.readinessStatus}</span>
      </div>

      {error ? <div className="rounded-xl border border-rose-100 bg-rose-50 p-3 text-sm text-rose-700">{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">Trials</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.trialWorkspaces}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Ready</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.readyForCheckpoint}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Recorded</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.checkpointRecorded}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Verified evidence</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.verifiedProviderSyncEvidence}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Paid-like signal</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.paidLikeProviderSignals}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Due soon</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.dueWithinSevenDays}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Expired</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.expiredTrials}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Checkpoint flag</div><div className="mt-1 text-sm font-semibold text-slate-900">{review.environment.checkpointEnabled ? "On" : "Locked"}</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">Workspace status mutation is {review.guardrails.workspaceStatusMutationActive ? "on" : "off"}. Trial conversion is {review.guardrails.trialConvertedToPaid ? "active" : "not active"}. Payment collection, customer portal activation, hard billing gates, broker distribution, owned portal rules, and internal load-board access remain unchanged.</div>
      </div>

      <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-6">
        {review.checks.map((check) => (
          <div key={check.key} className="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <div className="font-semibold text-slate-900">{check.label}</div>
              <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(check.status)}`}>{check.status}</span>
            </div>
            <p className="mt-2 text-sm leading-6 text-slate-600">{check.detail}</p>
            <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">First fix:</span> {check.firstFix}</div>
          </div>
        ))}
      </div>

      <div className="grid gap-3 md:grid-cols-4">
        <label className="text-sm font-medium text-slate-700">Checkpoint 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 trial rows</option>
            <option value="ready">Ready for checkpoint</option>
            <option value="recorded">Checkpoint recorded</option>
            <option value="needsReview">Needs review</option>
            <option value="dueSoon">Trial ends within 7 days</option>
            <option value="expired">Past trial end</option>
            <option value="missing_verified_test_sync">Missing verified test sync</option>
            <option value="missing_paid_like_provider_signal">Missing paid-like signal</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700 md:col-span-2">Search
          <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Workspace, plan, provider status, evidence..." className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm" />
        </label>
        <div className="flex items-end gap-2">
          <button type="button" onClick={exportRows} className="w-full rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white">Export rows</button>
          <button type="button" onClick={exportCheckpoints} className="w-full rounded-xl border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700">Export history</button>
        </div>
      </div>

      <label className="block text-sm font-medium text-slate-700">Checkpoint note
        <input value={note} onChange={(event) => setNote(event.target.value)} placeholder="Optional Super Admin note for recorded checkpoint evidence" className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm" />
      </label>

      <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">Trial checkpoint candidates</h3>
            <div className="text-sm text-slate-500">Filtered records: {rows.length}</div>
          </div>
          {rows.length === 0 ? <div className="rounded-xl bg-slate-50 p-4 text-sm text-slate-600">No trial checkpoint rows match the filters.</div> : rows.map((row) => (
            <div key={row.id} 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">{row.workspaceName}</div>
                  <div className="mt-1 text-xs text-slate-500">{row.workspaceType} · {row.accountClass} · {row.planName}</div>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                  <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(row.readinessStatus)}`}>{row.readinessStatus}</span>
                  <span className="rounded-full bg-white px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-slate-600">{row.checkpointLabel}</span>
                  <button
                    type="button"
                    disabled={!review.environment.checkpointEnabled || row.checkpointState !== "ready_for_checkpoint" || postingId === row.id}
                    onClick={() => recordCheckpoint(row)}
                    className="rounded-xl bg-blue-700 px-3 py-2 text-xs font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300"
                  >
                    {postingId === row.id ? "Recording..." : "Record checkpoint"}
                  </button>
                </div>
              </div>
              <div className="mt-3 grid gap-2 text-xs text-slate-600 md:grid-cols-3">
                <div><span className="font-semibold text-slate-900">Trial end:</span> {dateTime(row.trialEndsAt)}</div>
                <div><span className="font-semibold text-slate-900">Days left:</span> {row.daysRemaining ?? "Unknown"}</div>
                <div><span className="font-semibold text-slate-900">Provider:</span> {row.billingProviderStatus}</div>
                <div><span className="font-semibold text-slate-900">Sync:</span> {row.providerSyncStatus}</div>
                <div><span className="font-semibold text-slate-900">Customer:</span> {row.stripeCustomerIdMasked}</div>
                <div><span className="font-semibold text-slate-900">Subscription:</span> {row.stripeSubscriptionIdMasked}</div>
                <div><span className="font-semibold text-slate-900">Evidence:</span> {row.evidenceEventType}</div>
                <div className="break-all"><span className="font-semibold text-slate-900">Event ID:</span> {row.evidenceEventId}</div>
                <div><span className="font-semibold text-slate-900">Checkpoint:</span> {dateTime(row.checkpointRecordedAt)}</div>
              </div>
              <div className="mt-3 rounded-xl bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">First fix:</span> {row.firstFix}</div>
            </div>
          ))}
        </div>

        <div className="space-y-3">
          <h3 className="text-sm font-semibold text-slate-900">Recent checkpoint history</h3>
          {review.recentCheckpoints.length === 0 ? <div className="rounded-xl bg-slate-50 p-4 text-sm text-slate-600">No checkpoint records yet.</div> : review.recentCheckpoints.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.workspaceName}</div>
              <div className="mt-1 text-xs text-slate-500">{dateTime(event.createdAt)} · {event.reviewedBy}</div>
              <div className="mt-3 grid gap-2 text-xs text-slate-600">
                <div><span className="font-semibold text-slate-900">Status:</span> {event.currentStatus}</div>
                <div><span className="font-semibold text-slate-900">Provider:</span> {event.providerStatus}</div>
                <div className="break-all"><span className="font-semibold text-slate-900">Evidence:</span> {event.evidenceEventId}</div>
              </div>
              {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>
  );
}
