"use client";

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

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

type PortalCheck = {
  key: string;
  label: string;
  status: PortalStatus;
  detail: string;
  firstFix: string;
};

type PortalWorkspaceRow = {
  id: string;
  name: string;
  slug: string;
  workspaceType: string;
  accountClass: string;
  isActive: boolean;
  subscriptionStatus: string;
  billingProvider: string;
  billingMode: string;
  providerSyncStatus: string;
  stripeCustomerReady: boolean;
  stripeCustomerIdMasked: string;
  stripeSubscriptionIdMasked: string;
  planName: string;
  planBillingProvider: string;
  planBillingMode: string;
  planProviderSyncStatus: string;
  readinessStatus: PortalStatus;
  lockedTestSessionCandidate: boolean;
  portalUrlReturnReadyLater: boolean;
  firstFix: string;
};

type PortalEvent = {
  id: string;
  action: string;
  createdAt: string;
  reviewedBy: string | null;
  workspaceName: string | null;
  approved: boolean;
  readinessStatus: string;
  portalSessionCreated: boolean;
  portalUrlReturned: boolean;
  portalSessionIdMasked: string;
  lockReason: string;
  summary: string;
};

type PortalPreparationReview = {
  summary: {
    readinessStatus: PortalStatus;
    routeScaffoldActive: boolean;
    lockedPreparationActive: boolean;
    controlledUrlReturnReady?: boolean;
    workspacesReviewed: number;
    readyWorkspaces: number;
    checkWorkspaces: number;
    blockedWorkspaces: number;
    lockedPortalReviews: number;
    adminPreparationReviews: number;
    portalSessionsCreated: number;
    portalUrlsReturned: number;
    firstFix: string;
  };
  preparation: {
    mode: string;
    endpoint: string;
    method: string;
    stripeCallPrepared: string;
    stripeCallExecuted: boolean;
    portalSessionCreated: boolean;
    portalUrlReturned: boolean;
    expectedReturnPath: string;
    requestShape: { customer: string; return_url: string };
    reviewOnlyEffect: string;
  };
  environment: {
    stripeMode: string;
    secretKeyConfigured: boolean;
    portalFlagRequested: boolean;
    portalSessionFlagRequested: boolean;
    portalUrlReturnFlagRequested: boolean;
    paymentCollectionFlagRequested: boolean;
    hardBillingGateFlagRequested: boolean;
  };
  checks: PortalCheck[];
  workspaceRows: PortalWorkspaceRow[];
  recentEvents: PortalEvent[];
  guardrails: {
    reviewOnly: boolean;
    customerPortalRouteScaffoldActive: boolean;
    customerPortalTestSessionPreparationActive: boolean;
    customerPortalSessionCreationActive: boolean;
    customerPortalUrlReturnActive: boolean;
    paymentCollectionActive: boolean;
    webhookSubscriptionMutationActive: boolean;
    trialToPaidConversionActive: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

function statusClasses(status: PortalStatus) {
  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-slate-100 text-slate-700";
  return "bg-amber-100 text-amber-700";
}

function statusBorder(status: PortalStatus) {
  if (status === "Ready") return "border-emerald-100";
  if (status === "Blocked") return "border-rose-100";
  if (status === "Locked") return "border-slate-200";
  return "border-amber-100";
}

function dateTime(value?: string | null) {
  if (!value) return "Not recorded";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Needs review";
  return date.toLocaleString();
}

function csvCell(value: unknown) {
  const text = String(value ?? "").replace(/"/g, '""');
  return `"${text}"`;
}

function downloadCsv(filename: string, rows: Array<Record<string, unknown>>) {
  if (!rows.length) return;
  const headers = Object.keys(rows[0]);
  const csv = [headers.map(csvCell).join(","), ...rows.map((row) => headers.map((header) => csvCell(row[header])).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();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

export function AdminStripeCustomerPortalPreparationPanel() {
  const [review, setReview] = useState<PortalPreparationReview | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [note, setNote] = useState("");
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [filter, setFilter] = useState<"all" | PortalStatus>("all");

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

    async function loadReview() {
      try {
        setError(null);
        const data = await apiGet<PortalPreparationReview>("/api/admin/stripe-customer-portal/test-session-preparation");
        if (!cancelled) setReview(data);
      } catch (err: any) {
        if (!cancelled) setError(err?.message ?? "Failed to load customer portal preparation review.");
      } finally {
        if (!cancelled) setLoaded(true);
      }
    }

    void loadReview();

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

  const guardrailsClean = useMemo(() => review
    ? review.guardrails.reviewOnly
      && review.guardrails.customerPortalRouteScaffoldActive
      && review.guardrails.customerPortalTestSessionPreparationActive
      && !review.guardrails.paymentCollectionActive
      && !review.guardrails.webhookSubscriptionMutationActive
      && !review.guardrails.trialToPaidConversionActive
      && !review.guardrails.hardBillingGatesChanged
      && !review.guardrails.brokerDistributionChanged
      && !review.guardrails.ownedPortalRulesChanged
      && !review.guardrails.internalLoadBoardAccessChanged
    : true, [review]);

  const filteredRows = useMemo(() => {
    const rows = review?.workspaceRows ?? [];
    if (filter === "all") return rows;
    return rows.filter((row) => row.readinessStatus === filter);
  }, [filter, review?.workspaceRows]);

  async function recordReview(approved: boolean) {
    setSaving(true);
    setMessage(null);
    try {
      const data = await apiPost<PortalPreparationReview>("/api/admin/stripe-customer-portal/test-session-preparation", { approved, note });
      setReview(data);
      setNote("");
      setMessage(approved ? "Customer portal controlled test-link review recorded. Live portal activation is still off." : "Customer portal preparation review recorded without approval. Live portal activation stays off.");
    } catch (err: any) {
      setMessage(err?.message ?? "Customer portal preparation review could not be recorded.");
    } finally {
      setSaving(false);
    }
  }

  function exportRows() {
    if (!review) return;
    downloadCsv("dispatchspot-customer-portal-locked-test-session-preparation.csv", review.workspaceRows.map((row) => ({
      workspace: row.name,
      slug: row.slug,
      workspaceType: row.workspaceType,
      accountClass: row.accountClass,
      active: row.isActive ? "Yes" : "No",
      readinessStatus: row.readinessStatus,
      lockedTestSessionCandidate: row.lockedTestSessionCandidate ? "Yes" : "No",
      subscriptionStatus: row.subscriptionStatus,
      billingProvider: row.billingProvider,
      billingMode: row.billingMode,
      providerSyncStatus: row.providerSyncStatus,
      stripeCustomerReady: row.stripeCustomerReady ? "Yes" : "No",
      stripeCustomerId: row.stripeCustomerIdMasked,
      stripeSubscriptionId: row.stripeSubscriptionIdMasked,
      planName: row.planName,
      planBillingProvider: row.planBillingProvider,
      planBillingMode: row.planBillingMode,
      planProviderSyncStatus: row.planProviderSyncStatus,
      firstFix: row.firstFix,
    })));
  }

  if (!loaded) {
    return <section className="rounded-2xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Loading customer portal controlled test-link preparation…</section>;
  }

  if (error) {
    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 <section className="rounded-2xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Customer portal preparation review is not available yet.</section>;
  }

  return (
    <section className="rounded-2xl border border-cyan-100 bg-cyan-50 p-6 shadow-sm">
      <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-cyan-700">Customer portal preparation</div>
          <h2 className="mt-1 text-lg font-semibold text-slate-900">Prepare controlled Stripe customer portal test-link review</h2>
          <p className="mt-1 max-w-4xl text-sm leading-6 text-cyan-900">
            This panel prepares the Billing Portal path for controlled Stripe test-link review. Test portal sessions and URLs can be used only behind explicit review flags. Live portal activation, payment collection, subscription mutation, trial conversion, hard billing gates, and access-rule changes remain off.
          </p>
        </div>
        <span className={`w-fit rounded-full px-3 py-1 text-xs font-semibold ${guardrailsClean ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}`}>
          {guardrailsClean ? "Portal guardrails clean" : "Review portal guardrails"}
        </span>
      </div>

      <div className="mt-5 grid gap-3 text-sm md:grid-cols-4 xl:grid-cols-8">
        <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Readiness</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.readinessStatus}</div></div>
        <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Reviewed</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.workspacesReviewed}</div></div>
        <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Ready</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.readyWorkspaces}</div></div>
        <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Check</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.checkWorkspaces}</div></div>
        <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Blocked</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.blockedWorkspaces}</div></div>
        <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Portal reviews</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.lockedPortalReviews}</div></div>
        <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Sessions</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.portalSessionsCreated}</div></div>
        <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">URLs returned</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.portalUrlsReturned}</div></div>
      </div>

      <div className="mt-5 grid gap-4 xl:grid-cols-[minmax(0,1fr)_420px]">
        <div className="space-y-4">
          <div className="rounded-2xl border border-cyan-100 bg-white p-4">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <h3 className="font-semibold text-slate-900">Controlled test-link preparation</h3>
                <p className="mt-1 text-sm leading-6 text-slate-500">{review.preparation.reviewOnlyEffect}</p>
              </div>
              <span className="w-fit rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">Test-only portal URL</span>
            </div>
            <div className="mt-3 grid gap-2 text-sm md:grid-cols-4">
              <div className="rounded-xl bg-slate-50 p-3"><div className="text-xs text-slate-500">Endpoint</div><div className="mt-1 font-semibold text-slate-900">{review.preparation.endpoint}</div></div>
              <div className="rounded-xl bg-slate-50 p-3"><div className="text-xs text-slate-500">Prepared call</div><div className="mt-1 font-semibold text-slate-900">{review.preparation.stripeCallPrepared}</div></div>
              <div className="rounded-xl bg-slate-50 p-3"><div className="text-xs text-slate-500">Executed</div><div className="mt-1 font-semibold text-slate-900">{review.preparation.stripeCallExecuted ? "Yes" : "No"}</div></div>
              <div className="rounded-xl bg-slate-50 p-3"><div className="text-xs text-slate-500">Return path</div><div className="mt-1 font-semibold text-slate-900">{review.preparation.expectedReturnPath}</div></div>
            </div>
          </div>

          <div className="rounded-2xl border border-cyan-100 bg-white p-4">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <h3 className="font-semibold text-slate-900">Workspace portal candidates</h3>
                <p className="mt-1 text-sm text-slate-500">These rows show which paid workspaces are ready for controlled Stripe test portal links.</p>
              </div>
              <div className="flex flex-wrap gap-2">
                {(["all", "Ready", "Check", "Blocked", "Locked"] as const).map((item) => (
                  <button key={item} type="button" onClick={() => setFilter(item)} className={`rounded-full border px-3 py-1 text-xs font-semibold ${filter === item ? "border-slate-900 bg-slate-900 text-white" : "border-slate-200 bg-white text-slate-700"}`}>{item}</button>
                ))}
                <button type="button" onClick={exportRows} className="rounded-full border border-cyan-200 bg-cyan-50 px-3 py-1 text-xs font-semibold text-cyan-800">Export CSV</button>
              </div>
            </div>
            <div className="mt-4 overflow-x-auto">
              <table className="min-w-full text-left text-sm">
                <thead className="text-xs uppercase tracking-[0.14em] text-slate-500">
                  <tr>
                    <th className="px-3 py-2">Workspace</th>
                    <th className="px-3 py-2">Readiness</th>
                    <th className="px-3 py-2">Plan</th>
                    <th className="px-3 py-2">Subscription</th>
                    <th className="px-3 py-2">Stripe customer</th>
                    <th className="px-3 py-2">First fix</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {filteredRows.slice(0, 12).map((row) => (
                    <tr key={row.id}>
                      <td className="px-3 py-3 align-top"><div className="font-semibold text-slate-900">{row.name}</div><div className="text-xs text-slate-500">{row.workspaceType} · {row.accountClass}</div></td>
                      <td className="px-3 py-3 align-top"><span className={`rounded-full px-2.5 py-1 text-xs font-semibold ${statusClasses(row.readinessStatus)}`}>{row.readinessStatus}</span></td>
                      <td className="px-3 py-3 align-top"><div className="text-slate-900">{row.planName}</div><div className="text-xs text-slate-500">{row.planBillingProvider}/{row.planBillingMode} · {row.planProviderSyncStatus}</div></td>
                      <td className="px-3 py-3 align-top"><div className="text-slate-900">{row.subscriptionStatus}</div><div className="text-xs text-slate-500">{row.billingProvider}/{row.billingMode} · {row.providerSyncStatus}</div></td>
                      <td className="px-3 py-3 align-top"><div className="text-slate-900">{row.stripeCustomerReady ? "Ready" : "Needs review"}</div><div className="text-xs text-slate-500">{row.stripeCustomerIdMasked}</div></td>
                      <td className="max-w-sm px-3 py-3 align-top text-xs leading-5 text-slate-600">{row.firstFix}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {!filteredRows.length ? <div className="rounded-xl border border-dashed p-4 text-sm text-slate-500">No customer portal candidates match this filter.</div> : null}
            </div>
          </div>
        </div>

        <aside className="space-y-4">
          <div className="rounded-2xl border border-cyan-100 bg-white p-4">
            <h3 className="font-semibold text-slate-900">Preparation checks</h3>
            <div className="mt-3 space-y-3">
              {review.checks.map((check) => (
                <div key={check.key} className={`rounded-xl border p-3 ${statusBorder(check.status)}`}>
                  <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.5 py-1 text-xs font-semibold ${statusClasses(check.status)}`}>{check.status}</span>
                  </div>
                  <div className="mt-1 text-xs leading-5 text-slate-500">{check.detail}</div>
                  <div className="mt-2 text-xs font-medium text-slate-700">{check.firstFix}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="rounded-2xl border border-cyan-100 bg-white p-4">
            <h3 className="font-semibold text-slate-900">Record Super Admin review</h3>
            <p className="mt-1 text-sm leading-6 text-slate-500">This records readiness evidence only. It does not activate live portal access or billing.</p>
            <textarea value={note} onChange={(event) => setNote(event.target.value)} placeholder="Optional review note" className="mt-3 min-h-24 w-full rounded-xl border border-slate-200 p-3 text-sm outline-none focus:border-cyan-400" />
            <div className="mt-3 flex flex-wrap gap-2">
              <button type="button" disabled={saving} onClick={() => recordReview(true)} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white disabled:opacity-60">{saving ? "Recording..." : "Record approval"}</button>
              <button type="button" disabled={saving} onClick={() => recordReview(false)} className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-800 disabled:opacity-60">Record review only</button>
            </div>
            {message ? <div className="mt-3 rounded-xl bg-slate-50 p-3 text-sm text-slate-700">{message}</div> : null}
            <div className="mt-3 rounded-xl bg-cyan-50 p-3 text-xs leading-5 text-cyan-900">{review.summary.firstFix}</div>
          </div>

          <div className="rounded-2xl border border-cyan-100 bg-white p-4">
            <h3 className="font-semibold text-slate-900">Recent portal review evidence</h3>
            <div className="mt-3 space-y-3">
              {review.recentEvents.slice(0, 6).map((event) => (
                <div key={event.id} className="rounded-xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">
                  <div className="font-semibold text-slate-900">{dateTime(event.createdAt)} · {event.workspaceName ?? "Platform"}</div>
                  <div>{event.summary}</div>
                  <div className="text-slate-500">Created: {event.portalSessionCreated ? "Yes" : "No"} · URL returned: {event.portalUrlReturned ? "Yes" : "No"}</div>
                </div>
              ))}
              {!review.recentEvents.length ? <div className="rounded-xl border border-dashed p-3 text-sm text-slate-500">No customer portal review events have been recorded yet.</div> : null}
            </div>
          </div>
        </aside>
      </div>
    </section>
  );
}
