"use client";

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

type WorkspaceEntitlementRowStatus = "Ready" | "Check" | "Blocked" | "Inactive";

type WorkspaceUsage = { users: number; trucks: number; phoneNumbers: number };

type WorkspaceLimitVisibility = {
  key: string;
  label: string;
  used: number;
  included: number;
  over: number;
  status: string;
  addOnPrice: number;
  addOnReady: boolean;
};

type WorkspaceEntitlementRow = {
  workspaceId: string;
  workspaceName: string;
  slug: string;
  isActive: boolean;
  workspaceType: string | null;
  workspaceTypeLabel: string;
  accountClass: string | null;
  accountClassLabel: string;
  status: WorkspaceEntitlementRowStatus;
  planSource: string;
  planName: string;
  planFamily: string;
  planVisibility: string;
  subscriptionStatus: string;
  billingProvider: string;
  billingMode: string;
  providerSyncStatus: string;
  trialEndsAt: string | null;
  daysUntilTrialEnd: number | null;
  usage: WorkspaceUsage;
  loads: number;
  entitlementStatus: string;
  enforcementReady: boolean;
  overLimitCount: number;
  lockedFeatureCount: number;
  readyAddOnCount: number;
  futureFeatureAddOnCount: number;
  missingAddOnPriceCount: number;
  estimatedAddOnRevenue: number;
  addOnsSaved: { extraUsers: number; extraTrucks: number; extraPhoneNumbers: number };
  firstFix: string;
  workspaceAdminMessage: string;
  superAdminMessage: string;
  limits: WorkspaceLimitVisibility[];
  featuresAllowed: string[];
  featuresLocked: string[];
  addOnItems: Array<{ key: string; label: string; status: string; over: number; unitPrice: number | null; superAdminAction: string }>;
};

type WorkspaceEntitlementVisibilityReview = {
  summary: {
    totalWorkspaces: number;
    readyCount: number;
    checkCount: number;
    blockedCount: number;
    inactiveCount: number;
    noSubscriptionCount: number;
    overLimitWorkspaceCount: number;
    addOnReadyWorkspaceCount: number;
    missingAddOnPriceWorkspaceCount: number;
    totalEstimatedAddOnRevenue: number;
    firstFix: string;
  };
  workspaceTypeSummary: Array<{ label: string; total: number; ready: number; needsReview: number; overLimit: number; addOnReady: number }>;
  workspaceRows: WorkspaceEntitlementRow[];
  guardrails: {
    reviewOnly: boolean;
    schemaChanged: boolean;
    existingPlanFieldsOnly: boolean;
    paymentCollectionActive: boolean;
    customerPortalSessionsActive: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

const statusOptions = ["All", "Ready", "Check", "Blocked", "Inactive"] as const;
const addOnOptions = ["All", "Over limit", "Ready add-on", "Missing add-on price", "Future feature add-on"] as const;

function statusClasses(status: WorkspaceEntitlementRowStatus | string) {
  if (status === "Ready") return "bg-emerald-100 text-emerald-700";
  if (status === "Blocked") return "bg-rose-100 text-rose-700";
  if (status === "Inactive") return "bg-slate-100 text-slate-600";
  return "bg-amber-100 text-amber-700";
}

function borderClasses(status: WorkspaceEntitlementRowStatus) {
  if (status === "Ready") return "border-emerald-100";
  if (status === "Blocked") return "border-rose-100";
  if (status === "Inactive") return "border-slate-200";
  return "border-amber-100";
}

function csvEscape(value: unknown) {
  const text = Array.isArray(value) ? value.join("; ") : 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 money(value: number) {
  return `$${Number(value || 0).toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
}

function formatDate(value: string | null) {
  if (!value) return "—";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "—";
  return date.toLocaleDateString();
}

function trialLabel(row: WorkspaceEntitlementRow) {
  if (row.subscriptionStatus !== "TRIAL") return row.subscriptionStatus;
  if (row.daysUntilTrialEnd === null) return "Trial date missing";
  if (row.daysUntilTrialEnd < 0) return `Trial expired ${Math.abs(row.daysUntilTrialEnd)} days ago`;
  if (row.daysUntilTrialEnd === 0) return "Trial ends today";
  return `Trial ends in ${row.daysUntilTrialEnd} days`;
}

export function AdminWorkspaceEntitlementVisibilityPanel() {
  const [review, setReview] = useState<WorkspaceEntitlementVisibilityReview | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState<(typeof statusOptions)[number]>("All");
  const [typeFilter, setTypeFilter] = useState("All");
  const [addOnFilter, setAddOnFilter] = useState<(typeof addOnOptions)[number]>("All");
  const [search, setSearch] = useState("");

  async function loadReview() {
    try {
      setLoading(true);
      setMessage(null);
      const data = await apiGet<WorkspaceEntitlementVisibilityReview>("/api/admin/workspace-entitlements/review");
      setReview(data);
    } catch (error: any) {
      setMessage(error?.message ?? "Failed to load workspace entitlement visibility review");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { void loadReview(); }, []);

  const workspaceTypeOptions = useMemo(() => ["All", ...Array.from(new Set((review?.workspaceRows ?? []).map((row) => row.workspaceTypeLabel))).sort()], [review]);

  const filteredRows = useMemo(() => {
    const query = search.trim().toLowerCase();
    return (review?.workspaceRows ?? []).filter((row) => {
      if (statusFilter !== "All" && row.status !== statusFilter) return false;
      if (typeFilter !== "All" && row.workspaceTypeLabel !== typeFilter) return false;
      if (addOnFilter === "Over limit" && row.overLimitCount === 0) return false;
      if (addOnFilter === "Ready add-on" && row.readyAddOnCount === 0) return false;
      if (addOnFilter === "Missing add-on price" && row.missingAddOnPriceCount === 0) return false;
      if (addOnFilter === "Future feature add-on" && row.futureFeatureAddOnCount === 0) return false;
      if (!query) return true;
      return [
        row.workspaceName,
        row.slug,
        row.workspaceTypeLabel,
        row.accountClassLabel,
        row.planName,
        row.planFamily,
        row.planVisibility,
        row.subscriptionStatus,
        row.billingProvider,
        row.billingMode,
        row.providerSyncStatus,
        row.firstFix,
        row.featuresAllowed.join(" "),
        row.featuresLocked.join(" "),
      ].join(" ").toLowerCase().includes(query);
    });
  }, [review, statusFilter, typeFilter, addOnFilter, search]);

  function exportWorkspaceRows() {
    downloadCsv(
      "dispatchspot-workspace-entitlement-visibility-" + new Date().toISOString().slice(0, 10) + ".csv",
      ["Workspace", "Slug", "Status", "Workspace type", "Account class", "Plan", "Plan source", "Subscription", "Trial end", "Users", "Trucks", "Phone numbers", "Over limits", "Locked features", "Ready add-ons", "Missing add-on prices", "Estimated add-on revenue", "First fix"],
      filteredRows.map((row) => [
        row.workspaceName,
        row.slug,
        row.status,
        row.workspaceTypeLabel,
        row.accountClassLabel,
        row.planName,
        row.planSource,
        row.subscriptionStatus,
        row.trialEndsAt ?? "",
        row.usage.users,
        row.usage.trucks,
        row.usage.phoneNumbers,
        row.overLimitCount,
        row.lockedFeatureCount,
        row.readyAddOnCount,
        row.missingAddOnPriceCount,
        row.estimatedAddOnRevenue,
        row.firstFix,
      ]),
    );
  }

  function exportAddOnRows() {
    const rows = filteredRows.flatMap((row) => row.addOnItems.map((item) => [
      row.workspaceName,
      row.slug,
      row.planName,
      row.subscriptionStatus,
      item.label,
      item.status,
      item.over,
      item.unitPrice ?? "",
      row.estimatedAddOnRevenue,
      item.superAdminAction,
    ]));
    downloadCsv(
      "dispatchspot-workspace-add-on-readiness-" + new Date().toISOString().slice(0, 10) + ".csv",
      ["Workspace", "Slug", "Plan", "Subscription", "Add-on", "Status", "Over", "Unit price", "Workspace estimated add-on revenue", "Super Admin action"],
      rows,
    );
  }

  if (loading && !review) {
    return <section className="rounded-2xl border border-blue-100 bg-white p-6 text-sm text-slate-600 shadow-sm">Loading workspace entitlement visibility...</section>;
  }

  if (!review) {
    return <section className="rounded-2xl border border-rose-100 bg-rose-50 p-6 text-sm text-rose-700 shadow-sm">{message ?? "Workspace entitlement visibility is unavailable."}</section>;
  }

  return (
    <section className="rounded-2xl border border-blue-100 bg-blue-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-blue-700">Workspace entitlement visibility</div>
          <h2 className="mt-1 text-lg font-semibold text-slate-900">Review workspace usage, limits, and add-on readiness</h2>
          <p className="mt-1 max-w-4xl text-sm leading-6 text-blue-950">
            This Super Admin review shows how each workspace fits its saved plan before payment collection, customer portal sessions, or hard billing gates are activated.
          </p>
        </div>
        <div className="grid gap-2 text-sm sm:grid-cols-3 xl:min-w-[680px]">
          <div className="rounded-xl border border-blue-100 bg-white p-3"><div className="text-xs text-slate-500">Workspaces</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.totalWorkspaces}</div></div>
          <div className="rounded-xl border border-blue-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.readyCount}</div></div>
          <div className="rounded-xl border border-blue-100 bg-white p-3"><div className="text-xs text-slate-500">Need review</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.checkCount}</div></div>
          <div className="rounded-xl border border-blue-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.blockedCount}</div></div>
          <div className="rounded-xl border border-blue-100 bg-white p-3"><div className="text-xs text-slate-500">Over limits</div><div className="mt-1 text-xl font-semibold text-slate-900">{review.summary.overLimitWorkspaceCount}</div></div>
          <div className="rounded-xl border border-blue-100 bg-white p-3"><div className="text-xs text-slate-500">Est. add-ons</div><div className="mt-1 text-xl font-semibold text-slate-900">{money(review.summary.totalEstimatedAddOnRevenue)}</div></div>
        </div>
      </div>

      <div className="mt-4 rounded-xl border border-blue-100 bg-white p-3 text-sm leading-6 text-blue-950">
        <span className="font-semibold text-slate-900">First fix:</span> {review.summary.firstFix}
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-4">
        {review.workspaceTypeSummary.map((item) => (
          <div key={item.label} className="rounded-xl border border-blue-100 bg-white p-3 text-sm">
            <div className="font-semibold text-slate-900">{item.label}</div>
            <div className="mt-2 grid grid-cols-2 gap-2 text-xs text-slate-600">
              <div>Total: <span className="font-semibold text-slate-900">{item.total}</span></div>
              <div>Ready: <span className="font-semibold text-slate-900">{item.ready}</span></div>
              <div>Review: <span className="font-semibold text-slate-900">{item.needsReview}</span></div>
              <div>Add-ons: <span className="font-semibold text-slate-900">{item.addOnReady}</span></div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-5 rounded-2xl border border-blue-100 bg-white p-4">
        <div className="flex flex-col gap-3 xl:flex-row xl:items-end xl:justify-between">
          <div className="grid gap-3 md:grid-cols-4 xl:flex-1">
            <label className="block text-sm">
              <div className="mb-1 font-medium text-slate-700">Status</div>
              <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as (typeof statusOptions)[number])} className="w-full rounded-xl border px-3 py-2">
                {statusOptions.map((option) => <option key={option}>{option}</option>)}
              </select>
            </label>
            <label className="block text-sm">
              <div className="mb-1 font-medium text-slate-700">Workspace type</div>
              <select value={typeFilter} onChange={(event) => setTypeFilter(event.target.value)} className="w-full rounded-xl border px-3 py-2">
                {workspaceTypeOptions.map((option) => <option key={option}>{option}</option>)}
              </select>
            </label>
            <label className="block text-sm">
              <div className="mb-1 font-medium text-slate-700">Add-on review</div>
              <select value={addOnFilter} onChange={(event) => setAddOnFilter(event.target.value as (typeof addOnOptions)[number])} className="w-full rounded-xl border px-3 py-2">
                {addOnOptions.map((option) => <option key={option}>{option}</option>)}
              </select>
            </label>
            <label className="block text-sm">
              <div className="mb-1 font-medium text-slate-700">Search</div>
              <input value={search} onChange={(event) => setSearch(event.target.value)} className="w-full rounded-xl border px-3 py-2" placeholder="Workspace, plan, status..." />
            </label>
          </div>
          <div className="flex flex-wrap gap-2">
            <button type="button" onClick={() => { setStatusFilter("All"); setTypeFilter("All"); setAddOnFilter("All"); setSearch(""); }} className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700">Reset</button>
            <button type="button" onClick={exportWorkspaceRows} className="rounded-lg border border-blue-200 bg-blue-600 px-3 py-2 text-sm font-semibold text-white">Export workspace CSV</button>
            <button type="button" onClick={exportAddOnRows} className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700">Export add-ons CSV</button>
          </div>
        </div>

        <div className="mt-4 text-sm text-slate-600">Showing {filteredRows.length} of {review.workspaceRows.length} workspaces.</div>

        <div className="mt-4 grid gap-3 xl:grid-cols-2">
          {filteredRows.map((row) => (
            <div key={row.workspaceId} className={`rounded-2xl border bg-white p-4 shadow-sm ${borderClasses(row.status)}`}>
              <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                <div>
                  <div className="font-semibold text-slate-900">{row.workspaceName}</div>
                  <div className="mt-1 text-xs text-slate-500">/{row.slug} · {row.workspaceTypeLabel} · {row.accountClassLabel}</div>
                </div>
                <span className={`w-fit rounded-full px-2 py-0.5 text-[10px] font-semibold ${statusClasses(row.status)}`}>{row.status}</span>
              </div>

              <div className="mt-3 grid gap-2 text-xs md:grid-cols-3">
                <div className="rounded-lg bg-slate-50 p-2 text-slate-600"><span className="font-semibold text-slate-900">Plan:</span> {row.planName}<br />{row.planSource}</div>
                <div className="rounded-lg bg-slate-50 p-2 text-slate-600"><span className="font-semibold text-slate-900">Subscription:</span> {row.subscriptionStatus}<br />{trialLabel(row)}</div>
                <div className="rounded-lg bg-slate-50 p-2 text-slate-600"><span className="font-semibold text-slate-900">Add-on estimate:</span> {money(row.estimatedAddOnRevenue)}<br />Missing prices: {row.missingAddOnPriceCount}</div>
              </div>

              <div className="mt-3 grid gap-2 text-xs md:grid-cols-3">
                {row.limits.map((limit) => (
                  <div key={limit.key} className="rounded-lg border bg-slate-50 px-2 py-2 text-slate-600">
                    <div className="flex items-center justify-between gap-2"><span className="font-semibold text-slate-800">{limit.label}</span><span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${limit.over > 0 ? "bg-amber-100 text-amber-700" : "bg-emerald-100 text-emerald-700"}`}>{limit.status}</span></div>
                    <div className="mt-1">Used {limit.used} / included {limit.included}</div>
                    <div>Over {limit.over} · Add-on {money(limit.addOnPrice)}</div>
                  </div>
                ))}
              </div>

              <div className="mt-3 grid gap-2 text-xs md:grid-cols-2">
                <div className="rounded-lg border border-emerald-100 bg-emerald-50 p-2 text-emerald-800">Allowed: {row.featuresAllowed.length ? row.featuresAllowed.slice(0, 6).join(", ") : "None yet"}</div>
                <div className="rounded-lg border border-amber-100 bg-amber-50 p-2 text-amber-800">Locked/review: {row.featuresLocked.length ? row.featuresLocked.slice(0, 5).join(", ") : "None"}</div>
              </div>

              <div className="mt-3 rounded-lg border border-blue-100 bg-blue-50 p-2 text-xs leading-5 text-blue-900"><span className="font-semibold text-slate-900">First fix:</span> {row.firstFix}</div>
              <div className="mt-2 text-xs leading-5 text-slate-600">Workspace Admin message: {row.workspaceAdminMessage}</div>
              <div className="mt-1 text-xs leading-5 text-slate-500">Trial end: {formatDate(row.trialEndsAt)} · Provider: {row.billingProvider}/{row.billingMode}/{row.providerSyncStatus}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="mt-4 rounded-xl border border-blue-100 bg-white p-3 text-xs leading-5 text-blue-950">
        <span className="font-semibold">Guardrail:</span> this is Super Admin review-only visibility. It does not activate payment collection, customer portal sessions, hard billing gates, broker distribution limits, owned portal rules, or internal load-board access.
      </div>
      {message ? <div className="mt-3 rounded-xl border border-rose-100 bg-white p-3 text-sm text-rose-700">{message}</div> : null}
    </section>
  );
}
