"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { apiGet } from "@/lib/api";
import type { Organization, User } from "@/types";
import type { SubscriptionPlanDraft } from "@/src/modules/subscriptions/subscription-entitlements";

type WorkspaceSubscriptionPreview = {
  id: string;
  status: string;
  subscriptionPlanId: string;
  billingProvider?: string | null;
  billingMode?: string | null;
  providerSyncStatus?: string | null;
  trialEndsAt?: string | null;
  currentPeriodEndsAt?: string | null;
  plan: SubscriptionPlanDraft;
};

type WorkspaceRow = Organization & {
  users?: Array<Pick<User, "id" | "email" | "firstName" | "lastName" | "isActive" | "role">>;
  workspaceSubscription?: WorkspaceSubscriptionPreview | null;
};

type ReadinessTone = "Ready" | "Check" | "Blocked" | "Planning";

type ChecklistItem = {
  key: string;
  title: string;
  status: ReadinessTone;
  detail: string;
  countLabel: string;
};

type CleanupRow = {
  id: string;
  title: string;
  detail: string;
  href: string;
  tone: ReadinessTone;
};

const workspaceTypeLabels: Record<string, string> = {
  DISPATCHER: "Dispatcher",
  COMPANY_FLEET: "Company / Fleet",
  CARRIER_OWNER_OPERATOR: "Carrier / Owner-Operator",
  FREIGHT_BROKER: "Freight Broker",
  SHIPPER_CUSTOMER: "Shipper / Customer",
  DRIVER_INTERFACE: "Driver Interface",
  INTERNAL_OPERATIONS: "Internal Operations",
  PLATFORM_MARKETPLACE: "Platform Marketplace",
};

const accountClassLabels: Record<string, string> = {
  PAID_WORKSPACE: "Paid workspace",
  OWNED_INTERFACE: "Owned interface",
  INVITED_PORTAL: "Invited portal",
  PLATFORM_LAYER: "Platform layer",
  INTERNAL_WORKSPACE: "Internal workspace",
};

const expectedAccountClassByWorkspaceType: Record<string, string> = {
  DISPATCHER: "PAID_WORKSPACE",
  COMPANY_FLEET: "PAID_WORKSPACE",
  CARRIER_OWNER_OPERATOR: "PAID_WORKSPACE",
  FREIGHT_BROKER: "PAID_WORKSPACE",
  SHIPPER_CUSTOMER: "INVITED_PORTAL",
  DRIVER_INTERFACE: "OWNED_INTERFACE",
  INTERNAL_OPERATIONS: "INTERNAL_WORKSPACE",
  PLATFORM_MARKETPLACE: "PLATFORM_LAYER",
};

const recommendedTypesByPlanFamily: Record<string, string[]> = {
  General: ["DISPATCHER", "COMPANY_FLEET", "CARRIER_OWNER_OPERATOR"],
  Dispatcher: ["DISPATCHER"],
  "Company / Fleet": ["COMPANY_FLEET"],
  "Carrier / Owner-Operator": ["CARRIER_OWNER_OPERATOR"],
  "Freight Broker": ["FREIGHT_BROKER"],
  "Shipper / Customer": ["SHIPPER_CUSTOMER"],
  Internal: ["INTERNAL_OPERATIONS", "PLATFORM_MARKETPLACE"],
};

const soldWorkspaceTypes = ["DISPATCHER", "COMPANY_FLEET", "CARRIER_OWNER_OPERATOR", "FREIGHT_BROKER"];

const toneClasses: Record<ReadinessTone, string> = {
  Ready: "border-emerald-100 bg-emerald-50 text-emerald-800",
  Check: "border-amber-100 bg-amber-50 text-amber-800",
  Blocked: "border-rose-100 bg-rose-50 text-rose-800",
  Planning: "border-blue-100 bg-blue-50 text-blue-800",
};

const toneBadgeClasses: Record<ReadinessTone, string> = {
  Ready: "bg-emerald-100 text-emerald-700",
  Check: "bg-amber-100 text-amber-700",
  Blocked: "bg-rose-100 text-rose-700",
  Planning: "bg-blue-100 text-blue-700",
};

function labelWorkspaceType(value?: string | null) {
  if (!value) return "Missing type";
  return workspaceTypeLabels[value] ?? value;
}

function labelAccountClass(value?: string | null) {
  if (!value) return "Missing account class";
  return accountClassLabels[value] ?? value;
}

function sameStringSet(first: string[], second: string[]) {
  if (first.length !== second.length) return false;
  const secondSet = new Set(second);
  return first.every((item) => secondSet.has(item));
}

function isPaidWorkspace(workspace: WorkspaceRow) {
  if (workspace.accountClass === "PAID_WORKSPACE") return true;
  if (!workspace.accountClass && workspace.workspaceType && soldWorkspaceTypes.includes(workspace.workspaceType)) return true;
  return false;
}

function planIssues(plan: SubscriptionPlanDraft) {
  const issues: string[] = [];
  const recommendedTypes = recommendedTypesByPlanFamily[plan.planFamily] ?? recommendedTypesByPlanFamily.General;

  if (!plan.visibleWorkspaceTypes.length) issues.push("No visible workspace type list is saved.");
  if (!sameStringSet(plan.visibleWorkspaceTypes, recommendedTypes)) issues.push(`Visible workspace types differ from the ${plan.planFamily} recommendation.`);
  if (plan.planFamily === "Internal" && plan.planVisibility !== "Internal") issues.push("Internal plans should normally use Internal visibility.");
  if (plan.planFamily !== "Internal" && plan.planVisibility === "Internal") issues.push("Customer-facing family is marked Internal.");
  if (plan.planVisibility === "Public" && plan.status !== "Live") issues.push("Public visibility is staged on a non-live plan.");
  if (plan.visibleWorkspaceTypes.includes("PLATFORM_MARKETPLACE") && plan.planFamily !== "Internal") issues.push("Platform Marketplace visibility should stay under internal policy.");
  if (plan.planFamily === "Freight Broker" && plan.featureAccess.loadBoard) issues.push("Broker load-board access still needs usage limits, audit, and Super Admin policy before release.");

  return issues;
}

function planIsRegistrationCandidate(plan: SubscriptionPlanDraft) {
  if (plan.status === "Retired") return false;
  if (!["Public", "Invite only"].includes(plan.planVisibility)) return false;
  if (plan.planFamily === "Internal") return false;
  if (!plan.visibleWorkspaceTypes.length) return false;
  if (plan.visibleWorkspaceTypes.includes("PLATFORM_MARKETPLACE") || plan.visibleWorkspaceTypes.includes("DRIVER_INTERFACE")) return false;
  return true;
}

export function AdminRegistrationReadinessChecklist() {
  const [plans, setPlans] = useState<SubscriptionPlanDraft[]>([]);
  const [workspaces, setWorkspaces] = useState<WorkspaceRow[]>([]);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

    async function loadReadiness() {
      try {
        setError(null);
        const [planData, workspaceData] = await Promise.all([
          apiGet<{ plans: SubscriptionPlanDraft[] }>("/api/subscriptions"),
          apiGet<{ workspaces: WorkspaceRow[] }>("/api/workspaces"),
        ]);
        if (cancelled) return;
        setPlans(planData.plans);
        setWorkspaces(workspaceData.workspaces);
        setLoaded(true);
      } catch (err: any) {
        if (cancelled) return;
        setError(err?.message ?? "Failed to load registration readiness.");
        setLoaded(true);
      }
    }

    void loadReadiness();

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

  const readiness = useMemo(() => {
    const activeWorkspaces = workspaces.filter((workspace) => workspace.isActive !== false);
    const missingClassification = activeWorkspaces.filter((workspace) => !workspace.workspaceType && !workspace.accountClass);
    const partialClassification = activeWorkspaces.filter((workspace) => Boolean(workspace.workspaceType) !== Boolean(workspace.accountClass));
    const accountClassMismatch = activeWorkspaces.filter((workspace) => {
      if (!workspace.workspaceType || !workspace.accountClass) return false;
      return expectedAccountClassByWorkspaceType[workspace.workspaceType] && expectedAccountClassByWorkspaceType[workspace.workspaceType] !== workspace.accountClass;
    });
    const paidWorkspaces = activeWorkspaces.filter(isPaidWorkspace);
    const paidMissingSubscription = paidWorkspaces.filter((workspace) => !workspace.workspaceSubscription);
    const paidPlanMismatch = paidWorkspaces.filter((workspace) => {
      const workspaceType = workspace.workspaceType;
      const plan = workspace.workspaceSubscription?.plan;
      if (!workspaceType || !plan) return false;
      return !plan.visibleWorkspaceTypes.includes(workspaceType);
    });
    const trialMissingEndDate = paidWorkspaces.filter((workspace) => workspace.workspaceSubscription?.status === "TRIAL" && !workspace.workspaceSubscription.trialEndsAt);
    const planRows = plans.map((plan) => ({ plan, issues: planIssues(plan) }));
    const plansNeedingReview = planRows.filter((item) => item.issues.length > 0);
    const registrationCandidatePlans = plans.filter(planIsRegistrationCandidate);
    const candidateTypeSet = new Set(registrationCandidatePlans.flatMap((plan) => plan.visibleWorkspaceTypes));
    const uncoveredSoldTypes = soldWorkspaceTypes.filter((type) => !candidateTypeSet.has(type));
    const stripeLivePlans = plans.filter((plan) => plan.billing?.provider === "Stripe" && plan.billing?.mode === "Live");
    const stripeErrorPlans = plans.filter((plan) => plan.billing?.syncStatus === "Error");
    const brokerLoadBoardPlans = plans.filter((plan) => plan.visibleWorkspaceTypes.includes("FREIGHT_BROKER") && plan.featureAccess.loadBoard);

    const classificationStatus: ReadinessTone = missingClassification.length || partialClassification.length || accountClassMismatch.length ? "Check" : "Ready";
    const planStatus: ReadinessTone = plansNeedingReview.length ? "Check" : "Ready";
    const candidateStatus: ReadinessTone = registrationCandidatePlans.length === 0 ? "Planning" : uncoveredSoldTypes.length ? "Check" : "Ready";
    const subscriptionStatus: ReadinessTone = paidMissingSubscription.length || paidPlanMismatch.length ? "Blocked" : trialMissingEndDate.length ? "Check" : "Ready";
    const billingStatus: ReadinessTone = stripeErrorPlans.length ? "Blocked" : stripeLivePlans.length ? "Check" : "Planning";
    const policyStatus: ReadinessTone = brokerLoadBoardPlans.length ? "Planning" : "Ready";

    const checklist: ChecklistItem[] = [
      {
        key: "classification",
        title: "Workspace classification is clean",
        status: classificationStatus,
        countLabel: `${Math.max(activeWorkspaces.length - missingClassification.length - partialClassification.length - accountClassMismatch.length, 0)} / ${activeWorkspaces.length}`,
        detail: classificationStatus === "Ready"
          ? "Every active workspace has a stored workspace type and matching account class."
          : `${missingClassification.length} missing, ${partialClassification.length} partial, and ${accountClassMismatch.length} account-class mismatch record${accountClassMismatch.length === 1 ? "" : "s"} need review.`,
      },
      {
        key: "plan-visibility",
        title: "Plan visibility metadata is ready",
        status: planStatus,
        countLabel: `${Math.max(plans.length - plansNeedingReview.length, 0)} / ${plans.length}`,
        detail: planStatus === "Ready"
          ? "Saved plans have family, visibility, and visible workspace type values that match current recommendations."
          : `${plansNeedingReview.length} plan${plansNeedingReview.length === 1 ? "" : "s"} need family or workspace-type visibility cleanup before registration reads them.`,
      },
      {
        key: "candidate-plans",
        title: "Registration plan choices are staged",
        status: candidateStatus,
        countLabel: `${registrationCandidatePlans.length} candidate${registrationCandidatePlans.length === 1 ? "" : "s"}`,
        detail: registrationCandidatePlans.length === 0
          ? "No Public or Invite only customer plans are staged yet. Signup will show the workspace-type step and use a safe default plan until Super Admin stages at least one approved candidate."
          : uncoveredSoldTypes.length
            ? `Candidate plans exist, but these paid workspace types still have no staged choice: ${uncoveredSoldTypes.map(labelWorkspaceType).join(", ")}.`
            : "Every primary paid workspace type has at least one staged Public or Invite only plan choice for review-only signup.",
      },
      {
        key: "subscription-fit",
        title: "Existing paid workspaces fit their plans",
        status: subscriptionStatus,
        countLabel: `${Math.max(paidWorkspaces.length - paidMissingSubscription.length - paidPlanMismatch.length, 0)} / ${paidWorkspaces.length}`,
        detail: subscriptionStatus === "Ready"
          ? "Every active paid workspace has a subscription and its assigned plan is visible for that stored workspace type."
          : subscriptionStatus === "Blocked"
            ? `${paidMissingSubscription.length} paid workspace${paidMissingSubscription.length === 1 ? "" : "s"} missing subscription and ${paidPlanMismatch.length} assigned plan/type mismatch record${paidPlanMismatch.length === 1 ? "" : "s"} need cleanup.`
            : `${trialMissingEndDate.length} trial workspace${trialMissingEndDate.length === 1 ? "" : "s"} need a trial end date before trial behavior is shown during registration.`,
      },
      {
        key: "billing-safety",
        title: "Stripe and billing stay guarded",
        status: billingStatus,
        countLabel: `${stripeLivePlans.length} live Stripe plan${stripeLivePlans.length === 1 ? "" : "s"}`,
        detail: stripeErrorPlans.length
          ? `${stripeErrorPlans.length} plan${stripeErrorPlans.length === 1 ? "" : "s"} show Stripe sync errors. Fix those before any checkout or billing handoff work.`
          : stripeLivePlans.length
            ? "At least one saved plan is marked Stripe Live. Review carefully before registration or checkout work uses it."
            : "No live Stripe checkout is active here. Registration staging should remain a review-only step until Stripe is intentionally enabled.",
      },
      {
        key: "policy-gates",
        title: "Broker and marketplace access remain controlled",
        status: policyStatus,
        countLabel: `${brokerLoadBoardPlans.length} broker load-board plan${brokerLoadBoardPlans.length === 1 ? "" : "s"}`,
        detail: brokerLoadBoardPlans.length
          ? "Some broker-visible plans include load-board access. Keep broker distribution, usage limits, audit, and marketplace access out of registration until policy gates are built."
          : "No broker load-board plan needs urgent policy cleanup before the next registration staging step.",
      },
    ];

    const workspaceCleanupRows: CleanupRow[] = [
      ...[...missingClassification, ...partialClassification].map((workspace) => ({
        id: `classification-${workspace.id}`,
        title: workspace.name,
        detail: `Classification needs review: ${labelWorkspaceType(workspace.workspaceType)} · ${labelAccountClass(workspace.accountClass)}.`,
        href: "/admin/workspaces/types",
        tone: "Check" as ReadinessTone,
      })),
      ...accountClassMismatch.map((workspace) => ({
        id: `account-class-${workspace.id}`,
        title: workspace.name,
        detail: `${labelWorkspaceType(workspace.workspaceType)} should usually be ${labelAccountClass(expectedAccountClassByWorkspaceType[workspace.workspaceType ?? ""])}. Saved as ${labelAccountClass(workspace.accountClass)}.`,
        href: "/admin/workspaces/types",
        tone: "Check" as ReadinessTone,
      })),
      ...paidMissingSubscription.map((workspace) => ({
        id: `subscription-${workspace.id}`,
        title: workspace.name,
        detail: "Paid workspace candidate is missing a workspace subscription.",
        href: "/admin/workspaces/subscriptions",
        tone: "Blocked" as ReadinessTone,
      })),
      ...paidPlanMismatch.map((workspace) => ({
        id: `plan-fit-${workspace.id}`,
        title: workspace.name,
        detail: `${workspace.workspaceSubscription?.plan.name ?? "Assigned plan"} is not visible for ${labelWorkspaceType(workspace.workspaceType)}.`,
        href: "/admin/workspaces/types",
        tone: "Blocked" as ReadinessTone,
      })),
      ...trialMissingEndDate.map((workspace) => ({
        id: `trial-${workspace.id}`,
        title: workspace.name,
        detail: "Trial workspace does not have a trial end date saved yet.",
        href: "/admin/workspaces/subscriptions",
        tone: "Check" as ReadinessTone,
      })),
    ];

    const planCleanupRows: CleanupRow[] = plansNeedingReview.map(({ plan, issues }) => ({
      id: `plan-${plan.id}`,
      title: plan.name,
      detail: issues[0] ?? "Plan needs review.",
      href: "/admin/subscriptions",
      tone: issues.some((issue) => issue.includes("error") || issue.includes("Internal")) ? "Blocked" : "Check",
    }));

    const readyCount = checklist.filter((item) => item.status === "Ready").length;
    const checkCount = checklist.filter((item) => item.status === "Check").length;
    const blockedCount = checklist.filter((item) => item.status === "Blocked").length;
    const planningCount = checklist.filter((item) => item.status === "Planning").length;

    return {
      checklist,
      workspaceCleanupRows: workspaceCleanupRows.slice(0, 8),
      planCleanupRows: planCleanupRows.slice(0, 8),
      stats: {
        activeWorkspaces: activeWorkspaces.length,
        plans: plans.length,
        readyCount,
        checkCount,
        blockedCount,
        planningCount,
        registrationCandidatePlans: registrationCandidatePlans.length,
      },
    };
  }, [plans, workspaces]);

  if (!loaded) {
    return <section className="rounded-2xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Loading registration readiness checklist...</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>;
  }

  return (
    <section className="rounded-2xl border border-indigo-100 bg-indigo-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-indigo-700">Registration readiness checklist</div>
          <h2 className="mt-1 text-lg font-semibold text-slate-900">Confirm signup and plan-selection prerequisites first</h2>
          <p className="mt-1 max-w-4xl text-sm leading-6 text-indigo-900">
            This review tells Super Admin what must be cleaned up while signup uses workspace type and plan selection in review-only trial mode. It does not activate Stripe checkout, billing gates, broker distribution, owned portal rules, or internal load-board access.
          </p>
        </div>
        <div className="grid gap-2 text-sm sm:grid-cols-4 xl:min-w-[520px]">
          <div className="rounded-xl border border-indigo-100 bg-white p-3"><div className="text-xs text-slate-500">Ready checks</div><div className="mt-1 text-xl font-semibold text-slate-900">{readiness.stats.readyCount}</div></div>
          <div className="rounded-xl border border-indigo-100 bg-white p-3"><div className="text-xs text-slate-500">Needs review</div><div className="mt-1 text-xl font-semibold text-slate-900">{readiness.stats.checkCount}</div></div>
          <div className="rounded-xl border border-indigo-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">{readiness.stats.blockedCount}</div></div>
          <div className="rounded-xl border border-indigo-100 bg-white p-3"><div className="text-xs text-slate-500">Candidate plans</div><div className="mt-1 text-xl font-semibold text-slate-900">{readiness.stats.registrationCandidatePlans}</div></div>
        </div>
      </div>

      <div className="mt-5 grid gap-3 lg:grid-cols-2 xl:grid-cols-3">
        {readiness.checklist.map((item) => (
          <div key={item.key} className={`rounded-2xl border p-4 shadow-sm ${toneClasses[item.status]}`}>
            <div className="flex items-start justify-between gap-3">
              <div>
                <h3 className="font-semibold text-slate-900">{item.title}</h3>
                <div className="mt-1 text-xs font-semibold uppercase tracking-[0.14em] text-slate-500">{item.countLabel}</div>
              </div>
              <span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${toneBadgeClasses[item.status]}`}>{item.status}</span>
            </div>
            <p className="mt-3 text-sm leading-6 text-slate-700">{item.detail}</p>
          </div>
        ))}
      </div>

      <div className="mt-5 grid gap-4 xl:grid-cols-2">
        <div className="rounded-2xl border border-indigo-100 bg-white p-4">
          <div className="flex items-start justify-between gap-3">
            <div>
              <h3 className="font-semibold text-slate-900">Workspace cleanup queue</h3>
              <p className="mt-1 text-sm text-slate-500">The first records Super Admin should review before signup reads workspace type.</p>
            </div>
            <Link href="/admin/workspaces/types" className="rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700">Open types</Link>
          </div>
          <div className="mt-4 space-y-2">
            {readiness.workspaceCleanupRows.length ? readiness.workspaceCleanupRows.map((row) => (
              <Link key={row.id} href={row.href} className="block rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm transition hover:bg-white">
                <div className="flex items-start justify-between gap-3">
                  <div className="font-semibold text-slate-900">{row.title}</div>
                  <span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${toneBadgeClasses[row.tone]}`}>{row.tone}</span>
                </div>
                <div className="mt-1 text-xs leading-5 text-slate-600">{row.detail}</div>
              </Link>
            )) : <div className="rounded-xl border border-emerald-100 bg-emerald-50 p-3 text-sm text-emerald-800">No workspace cleanup rows are blocking registration staging review.</div>}
          </div>
        </div>

        <div className="rounded-2xl border border-indigo-100 bg-white p-4">
          <div className="flex items-start justify-between gap-3">
            <div>
              <h3 className="font-semibold text-slate-900">Plan cleanup queue</h3>
              <p className="mt-1 text-sm text-slate-500">The first plan metadata records to clean up before signup shows plan choices.</p>
            </div>
            <Link href="/admin/subscriptions" className="rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-700">Open plans</Link>
          </div>
          <div className="mt-4 space-y-2">
            {readiness.planCleanupRows.length ? readiness.planCleanupRows.map((row) => (
              <Link key={row.id} href={row.href} className="block rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm transition hover:bg-white">
                <div className="flex items-start justify-between gap-3">
                  <div className="font-semibold text-slate-900">{row.title}</div>
                  <span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${toneBadgeClasses[row.tone]}`}>{row.tone}</span>
                </div>
                <div className="mt-1 text-xs leading-5 text-slate-600">{row.detail}</div>
              </Link>
            )) : <div className="rounded-xl border border-emerald-100 bg-emerald-50 p-3 text-sm text-emerald-800">No plan cleanup rows are blocking registration staging review.</div>}
          </div>
        </div>
      </div>

      <div className="mt-5 flex flex-wrap gap-2">
        <Link href="/admin/workspaces/types" className="rounded-xl border border-indigo-200 bg-white px-3 py-2 text-sm font-semibold text-indigo-800">Review workspace types</Link>
        <Link href="/admin/workspaces/subscriptions" className="rounded-xl border border-indigo-200 bg-white px-3 py-2 text-sm font-semibold text-indigo-800">Review workspace subscriptions</Link>
        <Link href="/admin/stripe-readiness" className="rounded-xl border border-indigo-200 bg-white px-3 py-2 text-sm font-semibold text-indigo-800">Review Stripe readiness</Link>
      </div>
    </section>
  );
}
