"use client";

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

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

type WebhookCheck = {
  key: string;
  label: string;
  status: WebhookReviewStatus;
  detail: string;
  firstFix: string;
};

type WebhookEvent = {
  id: string;
  eventId: string;
  eventType: string;
  livemode: boolean;
  mode: string;
  signatureVerified: boolean;
  verificationStatus: string;
  handled: boolean;
  matchedWorkspaceName: string | null;
  matchedWorkspaceSlug: string | null;
  matchedWorkspaceSubscriptionId: string | null;
  customerIdMasked: string;
  subscriptionIdMasked: string;
  subscriptionItemIdMasked: string;
  providerSyncOutcome: string;
  workspaceSubscriptionStatus: string;
  errorNote: string;
  firstFix: string;
  createdAt: string;
};

type WebhookReview = {
  summary: {
    readinessStatus: WebhookReviewStatus;
    routeScaffoldActive: boolean;
    endpointPath: string;
    recentEventCount: number;
    lockedReviewEvents: number;
    verificationFailures: number;
    liveIgnoredEvents: number;
    matchedWorkspaceEvents: number;
    handledEvents: number;
    testSyncMutationsApplied: number;
    testSyncDuplicatesIgnored: number;
    testMutationAuditEvents: number;
    workspaceSubscriptionsWithStripeIds: number;
    firstFix: string;
  };
  environment: {
    stripeMode: string;
    secretKeyConfigured: boolean;
    publishableKeyConfigured: boolean;
    webhookSecretConfigured: boolean;
    webhookIntakeFlagRequested: boolean;
    subscriptionSyncFlagRequested: boolean;
    testSyncMutationFlagRequested: boolean;
    trialToPaidReviewOnly: boolean;
    paymentCollectionFlagRequested: boolean;
    customerPortalFlagRequested: boolean;
    hardBillingGateFlagRequested: boolean;
  };
  endpoint: {
    path: string;
    method: string;
    acceptsSignedStripeEvents: boolean;
    logsSanitizedMetadataOnly: boolean;
    subscriptionMutationAllowed: boolean;
    mutationScope: string;
  };
  supportedEvents: string[];
  checks: WebhookCheck[];
  recentEvents: WebhookEvent[];
  recentTestMutationAudit: Array<{
    id: string;
    summary: string;
    targetId: string | null;
    createdAt: string;
  }>;
  guardrails: {
    reviewOnly: boolean;
    verifiedTestProviderSyncMutationActive: boolean;
    subscriptionStatusMutationActive: boolean;
    checkoutSessionCreatedByWebhook: boolean;
    checkoutUrlReturnedByWebhook: boolean;
    paymentCollectionActive: boolean;
    customerPortalActive: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

function dateTime(value?: string | null) {
  if (!value) return "Not recorded";
  return new Date(value).toLocaleString();
}

function statusClasses(status: WebhookReviewStatus) {
  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 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 eventSearchText(event: WebhookEvent) {
  return [
    event.eventId,
    event.eventType,
    event.mode,
    event.verificationStatus,
    event.providerSyncOutcome,
    event.workspaceSubscriptionStatus,
    event.matchedWorkspaceName,
    event.matchedWorkspaceSlug,
    event.customerIdMasked,
    event.subscriptionIdMasked,
    event.subscriptionItemIdMasked,
    event.errorNote,
    event.firstFix,
  ].filter(Boolean).join(" ").toLowerCase();
}

export function AdminStripeWebhookLockedReviewPanel() {
  const [review, setReview] = useState<WebhookReview | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [eventFilter, setEventFilter] = useState("all");
  const [verificationFilter, setVerificationFilter] = useState("all");
  const [search, setSearch] = useState("");

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

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

    void loadReview();

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

  const eventTypes = useMemo(() => {
    const set = new Set<string>();
    review?.recentEvents.forEach((event) => set.add(event.eventType));
    return Array.from(set).sort();
  }, [review]);

  const filteredEvents = useMemo(() => {
    const needle = search.trim().toLowerCase();
    return (review?.recentEvents ?? []).filter((event) => {
      const matchesType = eventFilter === "all" || event.eventType === eventFilter
        || (eventFilter === "locked" && event.providerSyncOutcome.startsWith("locked_"))
        || (eventFilter === "matched" && Boolean(event.matchedWorkspaceName))
        || (eventFilter === "live" && event.livemode)
        || (eventFilter === "testMutation" && event.providerSyncOutcome === "test_subscription_sync_mutation_applied")
        || (eventFilter === "duplicateIgnored" && event.providerSyncOutcome === "test_subscription_sync_mutation_duplicate_ignored")
        || (eventFilter === "handled" && event.handled);
      const matchesVerification = verificationFilter === "all"
        || (verificationFilter === "verified" && event.signatureVerified)
        || (verificationFilter === "unsigned" && !event.signatureVerified && event.verificationStatus !== "verification_failed")
        || (verificationFilter === "failed" && event.verificationStatus === "verification_failed");
      const matchesSearch = !needle || eventSearchText(event).includes(needle);
      return matchesType && matchesVerification && matchesSearch;
    });
  }, [review, eventFilter, verificationFilter, search]);

  function exportEvents() {
    downloadCsv(
      "dispatchspot-stripe-webhook-locked-review-events.csv",
      ["Created", "Event type", "Event ID", "Mode", "Verified", "Verification", "Handled", "Workspace", "Customer ID", "Subscription/session ID", "Outcome", "Subscription status", "First fix", "Error"],
      filteredEvents.map((event) => [
        dateTime(event.createdAt),
        event.eventType,
        event.eventId,
        event.mode,
        event.signatureVerified ? "yes" : "no",
        event.verificationStatus,
        event.handled ? "yes" : "no",
        event.matchedWorkspaceName ?? "",
        event.customerIdMasked,
        event.subscriptionIdMasked,
        event.providerSyncOutcome,
        event.workspaceSubscriptionStatus,
        event.firstFix,
        event.errorNote,
      ]),
    );
  }

  if (!loaded) {
    return <section className="rounded-2xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Loading locked Stripe webhook review...</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 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">Stripe webhook locked scaffold</div>
          <h2 className="mt-1 text-xl font-semibold text-slate-900">Webhook review dashboard</h2>
          <p className="mt-1 max-w-4xl text-sm leading-6 text-slate-600">
            Review Stripe webhook route readiness and sanitized test-event logs before any webhook-driven subscription sync, payment collection, portal session, or billing gate is activated.
          </p>
        </div>
        <span className={`rounded-full px-3 py-1 text-xs font-semibold ${statusClasses(review.summary.readinessStatus)}`}>{review.summary.readinessStatus}</span>
      </div>

      <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">Recent events</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.recentEventCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Locked review</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.lockedReviewEvents}</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</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.recentEvents.filter((event) => event.signatureVerified).length}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Verify failed</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.verificationFailures}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Live ignored</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.liveIgnoredEvents}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Matched workspace</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.matchedWorkspaceEvents}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Handled</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.handledEvents}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Stripe IDs</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.workspaceSubscriptionsWithStripeIds}</div></div>
      </div>

      <div className="grid gap-3 md:grid-cols-3">
        <div className="rounded-xl border border-emerald-100 bg-emerald-50 p-3"><div className="text-xs font-semibold text-emerald-700">Verified test mutations</div><div className="mt-1 text-2xl font-semibold text-emerald-900">{review.summary.testSyncMutationsApplied}</div><p className="mt-1 text-xs leading-5 text-emerald-800">Provider sync fields only. Workspace status and access do not change.</p></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Duplicate ignored</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.testSyncDuplicatesIgnored}</div><p className="mt-1 text-xs leading-5 text-slate-600">Repeated event IDs are not applied twice.</p></div>
        <div className="rounded-xl border border-blue-100 bg-blue-50 p-3"><div className="text-xs font-semibold text-blue-700">Mutation scope</div><div className="mt-1 text-sm font-semibold text-blue-950">{review.endpoint.subscriptionMutationAllowed ? "Provider sync test mutation" : "Locked"}</div><p className="mt-1 text-xs leading-5 text-blue-800">{review.endpoint.mutationScope}</p></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">Endpoint:</span> <span className="font-mono">{review.endpoint.method} {review.endpoint.path}</span>
        <div className="mt-1 text-blue-800">{review.summary.firstFix}</div>
      </div>

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
        {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-4 lg:grid-cols-[1.2fr_0.8fr]">
        <div className="rounded-2xl border border-slate-100 bg-white p-4">
          <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Recent locked webhook event log</h3>
              <p className="mt-1 text-sm text-slate-500">Filtered records: {filteredEvents.length}</p>
            </div>
            <button type="button" onClick={exportEvents} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white">Export webhook CSV</button>
          </div>
          <div className="mt-4 grid gap-3 md:grid-cols-3">
            <label className="text-sm font-medium text-slate-700">Event filter
              <select value={eventFilter} onChange={(event) => setEventFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
                <option value="all">All events</option>
                <option value="locked">Locked review only</option>
                <option value="matched">Matched workspace</option>
                <option value="live">Live ignored</option>
                <option value="testMutation">Test mutation applied</option>
                <option value="duplicateIgnored">Duplicate ignored</option>
                <option value="handled">Handled</option>
                {eventTypes.map((type) => <option key={type} value={type}>{type}</option>)}
              </select>
            </label>
            <label className="text-sm font-medium text-slate-700">Verification
              <select value={verificationFilter} onChange={(event) => setVerificationFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
                <option value="all">All verification states</option>
                <option value="verified">Verified signatures</option>
                <option value="unsigned">Unsigned review</option>
                <option value="failed">Verification failed</option>
              </select>
            </label>
            <label className="text-sm font-medium text-slate-700">Search
              <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Workspace, event, ID, outcome..." className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm" />
            </label>
          </div>
          <div className="mt-4 space-y-3">
            {filteredEvents.length === 0 ? (
              <div className="rounded-xl border border-slate-100 bg-slate-50 p-4 text-sm text-slate-600">No webhook events match the current filters.</div>
            ) : filteredEvents.map((event) => (
              <div key={event.id} className="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-sm">
                <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
                  <div>
                    <div className="font-semibold text-slate-900">{event.eventType}</div>
                    <div className="mt-1 break-all text-xs text-slate-500">{event.eventId}</div>
                  </div>
                  <div className="flex flex-wrap gap-2 text-[10px] font-semibold uppercase tracking-[0.12em]">
                    <span className="rounded-full bg-white px-2 py-1 text-slate-700">{event.mode}</span>
                    <span className={`rounded-full px-2 py-1 ${event.providerSyncOutcome.startsWith("locked_") ? "bg-blue-100 text-blue-700" : event.handled ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}`}>{event.providerSyncOutcome}</span>
                    <span className={`rounded-full px-2 py-1 ${event.signatureVerified ? "bg-emerald-100 text-emerald-700" : event.verificationStatus === "verification_failed" ? "bg-rose-100 text-rose-700" : "bg-slate-100 text-slate-600"}`}>{event.signatureVerified ? "Verified" : event.verificationStatus}</span>
                  </div>
                </div>
                <div className="mt-3 grid gap-3 md:grid-cols-4">
                  <div><div className="text-xs font-semibold text-slate-900">Workspace</div><div className="mt-1 text-slate-600">{event.matchedWorkspaceName ?? "No match"}</div></div>
                  <div><div className="text-xs font-semibold text-slate-900">Customer</div><div className="mt-1 text-slate-600">{event.customerIdMasked}</div></div>
                  <div><div className="text-xs font-semibold text-slate-900">Subscription/session</div><div className="mt-1 text-slate-600">{event.subscriptionIdMasked}</div></div>
                  <div><div className="text-xs font-semibold text-slate-900">Received</div><div className="mt-1 text-slate-600">{dateTime(event.createdAt)}</div></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> {event.firstFix}</div>
                {event.errorNote ? <div className="mt-2 rounded-xl bg-rose-50 p-3 text-xs leading-5 text-rose-700">{event.errorNote}</div> : null}
              </div>
            ))}
          </div>
        </div>

        <div className="space-y-4">
          <div className="rounded-2xl border border-slate-100 bg-white p-4">
            <h3 className="text-sm font-semibold text-slate-900">Environment posture</h3>
            <div className="mt-3 space-y-2 text-sm text-slate-600">
              <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Stripe mode:</span> {review.environment.stripeMode}</div>
              <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Webhook secret:</span> {review.environment.webhookSecretConfigured ? "Present" : "Missing"}</div>
              <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Event intake flag:</span> {review.environment.webhookIntakeFlagRequested ? "On" : "Off"}</div>
              <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Subscription sync flag:</span> {review.environment.subscriptionSyncFlagRequested ? "On" : "Off"}</div>
              <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Test mutation flag:</span> {review.environment.testSyncMutationFlagRequested ? "On" : "Off"}</div>
              <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Trial conversion:</span> {review.environment.trialToPaidReviewOnly ? "Review-only" : "Flag conflict"}</div>
            </div>
          </div>
          <div className="rounded-2xl border border-slate-100 bg-white p-4">
            <h3 className="text-sm font-semibold text-slate-900">Supported review events</h3>
            <div className="mt-3 flex flex-wrap gap-2">
              {review.supportedEvents.map((event) => <span key={event} className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-600">{event}</span>)}
            </div>
          </div>
          <div className="rounded-2xl border border-amber-100 bg-amber-50 p-4 text-sm leading-6 text-amber-800">
            <span className="font-semibold">Safety lock:</span> v449 only allows verified Stripe test webhook provider-sync field updates behind explicit flags. It does not change workspace subscription status, convert trials to paid, collect payments, activate customer portal access, enforce billing gates, change broker distribution, change portal rules, or change internal load-board access.
          </div>
        </div>
      </div>
    </section>
  );
}
