"use client";

import { Fragment, useEffect, useState } from "react";
import { useDashboardAuth } from "@/components/layout/dashboard-auth-context";
import { usePreviewRole } from "@/components/layout/preview-context";
import { Field } from "@/components/shared/field";
import {
  DetailList,
  Panel,
  StatusBadge,
} from "@/components/shared/page";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { canManage } from "@/lib/preview";
import { BadgePercent } from "lucide-react";
import { SubscriptionPreview } from "./subscription-preview";
import {
  oneTimeOnlyCheckoutForPlan,
  planFeatureGroups,
  planFeaturesForTier,
} from "./plan-comparison";
import {
  cancelSubscription,
  createSubscription,
  getCurrentSubscription,
  getSubscriptionPlans,
  previewSubscriptionCheckout,
  subscriptionCreationDetails,
  type SubscriptionCheckoutPreview,
  type SubscriptionCreateBody,
  type SubscriptionCurrency,
  type SubscriptionPlan,
  type CurrentSubscription,
} from "./subscription-api";

type LoadState = "idle" | "loading" | "loaded" | "failed";
type PendingAction = "preview" | "create" | null;
type CreatedSubscription = {
  contractId?: string;
  invoiceId?: string;
  status?: string;
  invoiceStatus?: string;
  invoiceCurrency?: SubscriptionCurrency;
  invoiceTotalAmount?: number;
  invoiceDueAt?: string;
};
const uuidPattern =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function ContractDiscountCallout({ plan }: { plan: SubscriptionPlan }) {
  const contractDiscount =
    plan.tier === 2
      ? { duration: "1-year contract", percentage: "5%" }
      : plan.tier === 3
        ? { duration: "3-year contract", percentage: "10%" }
        : null;

  if (!contractDiscount) return null;

  const colorClasses =
    plan.tier === 2
      ? "border-plan-popular bg-plan-popular text-plan-popular-foreground"
      : "border-plan-gold bg-plan-gold text-plan-gold-foreground";

  return (
    <div
      className={`flex w-[148px] shrink-0 items-center justify-between gap-2 rounded-xl border-2 px-3 py-2 shadow-md ${colorClasses}`}
    >
      <div className="min-w-0">
        <p className="text-2xl leading-none font-black">
          {contractDiscount.percentage}
        </p>
        <p className="mt-1 text-[10px] leading-tight font-extrabold uppercase tracking-wide">
          {contractDiscount.duration} discount
        </p>
      </div>
      <BadgePercent className="size-5 shrink-0" aria-hidden="true" />
    </div>
  );
}

function formatMoney(value: number, currency: SubscriptionCurrency) {
  return new Intl.NumberFormat(currency === "IDR" ? "id-ID" : "en-US", {
    style: "currency",
    currency,
    maximumFractionDigits: 2,
  }).format(value);
}

function formatOneTimeAmount(
  value: number,
  currency: SubscriptionCurrency,
) {
  return new Intl.NumberFormat(currency === "IDR" ? "id-ID" : "en-US", {
    style: "currency",
    currency,
    maximumFractionDigits: 0,
  }).format(value);
}

function planLimit(plan: SubscriptionPlan) {
  if (plan.maxConnectors === null) return `${plan.minConnectors}+ connectors`;
  return `${plan.minConnectors}–${plan.maxConnectors} connectors`;
}

function getErrorMessage(error: unknown, fallback: string) {
  return error instanceof Error ? error.message : fallback;
}

function formatInvoiceDueAt(value?: string) {
  if (!value) return "Not returned";
  const date = new Date(value);
  return Number.isFinite(date.getTime()) ? date.toLocaleString() : value;
}

function subscriptionCountryCode(country: string): string | undefined {
  const normalized = country.trim();
  if (/^[a-z]{2}$/i.test(normalized)) return normalized.toUpperCase();
  if (normalized.toLowerCase() === "indonesia") return "ID";
  return undefined;
}

export function SubscriptionManagement() {
  const { apiConfigured, profile } = useDashboardAuth();
  const role = usePreviewRole();
  const editable = canManage(role);
  const currency: SubscriptionCurrency = "USD";
  const [subscriptionView, setSubscriptionView] = useState<"current" | "plans">("current");
  const [currentSubscription, setCurrentSubscription] =
    useState<CurrentSubscription | null>(null);
  const [currentSubscriptionState, setCurrentSubscriptionState] =
    useState<LoadState>("loading");
  const [currentSubscriptionError, setCurrentSubscriptionError] = useState("");
  const [currentSubscriptionReloadKey, setCurrentSubscriptionReloadKey] =
    useState(0);
  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [cancelBusy, setCancelBusy] = useState(false);
  const [cancelError, setCancelError] = useState("");
  const [cancelNotice, setCancelNotice] = useState("");
  const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
  const [plansState, setPlansState] = useState<LoadState>("loading");
  const [plansError, setPlansError] = useState("");
  const [reloadKey, setReloadKey] = useState(0);
  const [selectedPlanId, setSelectedPlanId] = useState("");
  const [checkoutDialogOpen, setCheckoutDialogOpen] = useState(false);
  const [connectorsDraft, setConnectorsDraft] = useState("");
  const [checkoutPreview, setCheckoutPreview] =
    useState<SubscriptionCheckoutPreview | null>(null);
  const [previewBodyKey, setPreviewBodyKey] = useState("");
  const [created, setCreated] = useState<CreatedSubscription | null>(null);
  const [pendingAction, setPendingAction] = useState<PendingAction>(null);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!apiConfigured || subscriptionView !== "current") return;
    const controller = new AbortController();
    void getCurrentSubscription(controller.signal)
      .then((result) => {
        if (controller.signal.aborted) return;
        setCurrentSubscription(result);
        setCurrentSubscriptionState("loaded");
      })
      .catch((loadError: unknown) => {
        if (controller.signal.aborted) return;
        setCurrentSubscriptionError(
          getErrorMessage(loadError, "Could not load the current subscription."),
        );
        setCurrentSubscriptionState("failed");
      });
    return () => controller.abort();
  }, [apiConfigured, subscriptionView, currentSubscriptionReloadKey]);

  useEffect(() => {
    if (!apiConfigured) return;
    const selectedCurrency = currency;
    const controller = new AbortController();
    async function loadPlans() {
      setPlansState("loading");
      setPlansError("");
      try {
        const result = await getSubscriptionPlans(
          selectedCurrency,
          controller.signal,
        );
        if (controller.signal.aborted) return;
        setPlans(result);
        setSelectedPlanId((current) =>
          result.some((plan) => plan.id === current)
            ? current
            : "",
        );
        setPlansState("loaded");
      } catch (loadError: unknown) {
        if (controller.signal.aborted) return;
        setPlans([]);
        setPlansState("failed");
        setPlansError(
          getErrorMessage(loadError, "Could not load subscription plans."),
        );
      }
    }
    void loadPlans();
    return () => controller.abort();
  }, [apiConfigured, currency, reloadKey]);

  const plan = plans.find((item) => item.id === selectedPlanId);
  const connectors =
    plan?.maxConnectors ?? Number(connectorsDraft);
  const connectorError = plan
    ? !Number.isSafeInteger(connectors) || connectors < 1
      ? "Enter a positive whole number of connectors."
      : connectors < plan.minConnectors
        ? `${plan.name} requires at least ${plan.minConnectors} connectors.`
        : plan.maxConnectors !== null && connectors > plan.maxConnectors
          ? `${plan.name} supports up to ${plan.maxConnectors} connectors.`
          : connectors > 100000
            ? "The subscription form supports up to 100,000 connectors."
            : undefined
    : undefined;
  function buildRequestBody(
    selectedPlan: SubscriptionPlan,
    connectorCount: number,
  ): SubscriptionCreateBody {
    const user: SubscriptionCreateBody["user"] = {};
    if (profile) {
      user.email = profile.email;
      user.name = [profile.firstName, profile.lastName].filter(Boolean).join(" ");
      user.phone_number = profile.phone;
      user.organization_code = profile.organizationCode;
      if (uuidPattern.test(profile.id)) user.user_id = profile.id;
      const country = subscriptionCountryCode(profile.address.country);
      if (country) user.country = country;
    }
    const checkoutPricing = oneTimeOnlyCheckoutForPlan(
      selectedPlan.name,
      selectedPlan.tier,
    );
    return {
      plan_id: selectedPlan.id,
      net_amount: checkoutPricing.netAmount,
      one_time_amount: checkoutPricing.oneTimeAmount,
      max_connectors: connectorCount,
      feature_strings: planFeaturesForTier(selectedPlan.tier),
      user,
      payment_summary: checkoutPricing.paymentSummary,
    };
  }
  const requestBody =
    plan && !connectorError ? buildRequestBody(plan, connectors) : null;

  const requestBodyKey = requestBody ? JSON.stringify(requestBody) : "";
  const invoicePaymentSummary = checkoutPreview
    ? checkoutPreview.paymentSummary.map((item) => ({
        ...item,
        isFree: item.amount === 0,
      }))
    : [];
  const previewIsCurrent =
    !!checkoutPreview && !!requestBodyKey && previewBodyKey === requestBodyKey;
  const busy = pendingAction !== null;
  const currentSubscriptionIsCancelled =
    currentSubscription !== null &&
    ["cancelled", "canceled"].includes(
      currentSubscription.status.toLowerCase(),
    );
  const canCancelCurrentSubscription =
    currentSubscription !== null &&
    ["active", "pending_payment"].includes(
      currentSubscription.status.toLowerCase(),
    );

  function selectPlan(planId: string) {
    const selectedPlan = plans.find((item) => item.id === planId);
    if (!selectedPlan || !editable || busy) return;

    setSelectedPlanId(planId);
    setConnectorsDraft("");
    setCheckoutPreview(null);
    setPreviewBodyKey("");
    setError("");
    setCheckoutDialogOpen(true);

    if (selectedPlan.maxConnectors !== null) {
      void requestPreview(
        buildRequestBody(selectedPlan, selectedPlan.maxConnectors),
      );
    }
  }

  if (!apiConfigured) return <SubscriptionPreview />;

  async function requestPreview(body: SubscriptionCreateBody | null = requestBody) {
    setError("");
    if (!editable || !body) return;
    setPendingAction("preview");
    try {
      const value = await previewSubscriptionCheckout(body);
      if (value.netAmount !== 0) {
        throw new Error(
          "The subscription service returned a recurring amount. Checkout requires a one-time-only quote.",
        );
      }
      setCheckoutPreview(value);
      setPreviewBodyKey(JSON.stringify(body));
    } catch (previewError: unknown) {
      setCheckoutPreview(null);
      setPreviewBodyKey("");
      setError(getErrorMessage(previewError, "Could not preview checkout."));
    } finally {
      setPendingAction(null);
    }
  }

  async function submitCreate() {
    setError("");
    if (!editable || !requestBody || !previewIsCurrent) return;
    setPendingAction("create");
    try {
      const result = await createSubscription(requestBody);
      const details = subscriptionCreationDetails(result);
      setCreated(details);
      setCheckoutDialogOpen(false);
    } catch (createError: unknown) {
      setError(getErrorMessage(createError, "Could not create the subscription."));
    } finally {
      setPendingAction(null);
    }
  }

  async function submitCancelSubscription() {
    if (!editable || !currentSubscription || !canCancelCurrentSubscription) {
      return;
    }
    setCancelError("");
    setCancelNotice("");
    setCancelBusy(true);
    try {
      await cancelSubscription(currentSubscription.id);
      setCurrentSubscription({ ...currentSubscription, status: "cancelled" });
      setCancelDialogOpen(false);
      setCancelNotice("Monet confirmed the subscription cancellation.");
    } catch (cancelFailure: unknown) {
      setCancelError(
        getErrorMessage(cancelFailure, "Could not cancel the subscription."),
      );
    } finally {
      setCancelBusy(false);
    }
  }

  function openCurrentSubscription() {
    setCreated(null);
    setCurrentSubscription(null);
    setCurrentSubscriptionState("loading");
    setCurrentSubscriptionError("");
    setCancelNotice("");
    setSubscriptionView("current");
  }

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-semibold">Subscription</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          {created
            ? "Your subscription has been created."
            : "View the tenant's current subscription or compare available plans."}
        </p>
      </div>

      {created ? (
        <section className="panel overflow-hidden">
          <div className="flex flex-col items-center px-6 py-12 text-center">
            <div
              aria-hidden="true"
              className="flex size-16 items-center justify-center rounded-full bg-success/15 text-4xl font-semibold text-success"
            >
              ✓
            </div>
            <p className="mt-5 text-xs font-semibold uppercase tracking-[0.16em] text-success">
              Subscription created
            </p>
            <h3 className="mt-2 text-3xl font-semibold">
              Thank you for subscribing.
            </h3>
            <p className="mt-3 max-w-xl text-sm text-muted-foreground">
              We appreciate your business and look forward to serving you.
            </p>
          </div>

          <div className="flex justify-center border-t p-5">
            <Button onClick={openCurrentSubscription}>
              View current subscription
            </Button>
          </div>
        </section>
      ) : (
        <>
      <div
        className="flex flex-wrap gap-2"
        role="group"
        aria-label="Subscription views"
      >
        <Button
          type="button"
          variant={subscriptionView === "current" ? "default" : "outline"}
          aria-pressed={subscriptionView === "current"}
          onClick={() => {
            setCheckoutDialogOpen(false);
            if (subscriptionView !== "current") {
              setCurrentSubscriptionState("loading");
              setCurrentSubscriptionError("");
              setCancelNotice("");
            }
            setSubscriptionView("current");
          }}
        >
          Current subscription
        </Button>
        <Button
          type="button"
          variant={subscriptionView === "plans" ? "default" : "outline"}
          aria-pressed={subscriptionView === "plans"}
          onClick={() => setSubscriptionView("plans")}
        >
          Subscription plans
        </Button>
      </div>

      {subscriptionView === "current" ? (
        <Panel
          title="Current subscription"
          description="Subscription details returned for this tenant."
        >
          {currentSubscriptionState === "loading" && (
            <p className="p-5 text-sm text-muted-foreground">
              Checking current subscription…
            </p>
          )}
          {currentSubscriptionState === "failed" && (
            <div className="flex flex-wrap items-center justify-between gap-4 p-5">
              <p role="alert" className="text-sm text-destructive">
                {currentSubscriptionError}
              </p>
              <Button
                variant="outline"
                onClick={() => {
                  setCurrentSubscriptionState("loading");
                  setCurrentSubscriptionError("");
                setCancelNotice("");
                  setCurrentSubscriptionReloadKey((current) => current + 1);
                }}
              >
                Try again
              </Button>
            </div>
          )}
          {currentSubscriptionState === "loaded" &&
            !currentSubscription && (
              <p role="status" className="p-6 text-center text-sm text-muted-foreground">
                This tenant has no subscription.
              </p>
            )}
          {currentSubscriptionState === "loaded" &&
            currentSubscription && (
              <>
                <DetailList
                  items={{
                    Plan: currentSubscription.planName ?? "Not returned",
                    Status: (
                      <StatusBadge>
                        {currentSubscription.status.replaceAll("_", " ")}
                      </StatusBadge>
                    ),
                    "Connector limit":
                      currentSubscription.maxConnectors ?? "Not returned",
                    "Contract number":
                      currentSubscription.contractNumber ?? currentSubscription.id,
                    Currency: currentSubscription.currency ?? "Not returned",
                    "Current period": [
                      currentSubscription.currentPeriodStart
                        ? formatInvoiceDueAt(currentSubscription.currentPeriodStart)
                        : "",
                      currentSubscription.currentPeriodEnd
                        ? formatInvoiceDueAt(currentSubscription.currentPeriodEnd)
                        : "",
                    ].filter(Boolean).join(" – ") || "Not returned",
                  }}
                />
                {(canCancelCurrentSubscription ||
                  (cancelNotice && currentSubscriptionIsCancelled) ||
                  cancelError) && (
                  <div className="flex flex-wrap items-center justify-between gap-4 border-t p-5">
                    <div className="space-y-1">
                      {cancelNotice && currentSubscriptionIsCancelled && (
                        <p role="status" className="text-sm text-success">
                          {cancelNotice}
                        </p>
                      )}
                      {cancelError && (
                        <p role="alert" className="text-sm text-destructive">
                          {cancelError}
                        </p>
                      )}
                    </div>
                    {canCancelCurrentSubscription && (
                      <Button
                        variant="destructive"
                        disabled={!editable || cancelBusy}
                        onClick={() => {
                          setCancelError("");
                          setCancelDialogOpen(true);
                        }}
                      >
                        Cancel subscription
                      </Button>
                    )}
                  </div>
                )}
              </>
            )}
        </Panel>
      ) : (
        <>
      <div>
        <h2 className="text-2xl font-semibold">Available Plans</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          Compare pricing and features to choose a plan. Plan names, connector
          limits, and per-connector prices come from Monet.
        </p>
      </div>

      {plansState === "loading" && (
        <Panel>
          <p className="p-5 text-sm text-muted-foreground">Loading plans…</p>
        </Panel>
      )}
      {plansState === "idle" && (
        <Panel title="Choose a currency">
          <p className="p-5 text-sm text-muted-foreground">
            Select IDR or USD to load the plans available in that currency.
          </p>
        </Panel>
      )}
      {plansState === "failed" && (
        <Panel title="Plans unavailable">
          <div className="space-y-3 p-5">
            <p role="alert" className="text-sm text-destructive">
              {plansError}
            </p>
            <Button
              variant="outline"
              onClick={() => {
                setSelectedPlanId("");
                setCheckoutPreview(null);
                setPreviewBodyKey("");
                setReloadKey((current) => current + 1);
              }}
            >
              Try again
            </Button>
          </div>
        </Panel>
      )}
      {plansState === "loaded" && plans.length === 0 && (
        <Panel title="No plans available">
          <p className="p-5 text-sm text-muted-foreground">
            Monet returned no plans in {currency}.
          </p>
        </Panel>
      )}
      {plans.length > 0 && (
        <div className="mx-auto grid w-full max-w-[1480px] grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {plans.map((item) => (
            <section
              key={item.id}
              className={`panel relative flex flex-col overflow-hidden ${item.recommended ? "border-2 border-plan-gold" : item.popular ? "border-2 border-plan-popular" : ""} ${selectedPlanId === item.id ? "ring-2 ring-primary" : ""}`}
            >
              <div
                className={`h-1 ${item.recommended ? "bg-plan-gold" : item.popular ? "bg-plan-popular" : "bg-muted"}`}
              />
              {(item.recommended || item.popular) && (
                <span
                  className={`absolute top-4 right-5 inline-flex items-center rounded-full px-3 py-1 text-xs font-bold tracking-wider shadow-sm ring-1 ${item.recommended ? "bg-plan-gold text-plan-gold-foreground ring-plan-gold" : "bg-plan-popular text-plan-popular-foreground ring-plan-popular"}`}
                >
                  {item.recommended ? "RECOMMENDED" : "POPULAR"}
                </span>
              )}
              <div className="flex flex-1 flex-col p-5">
                <h3
                  className={`text-xl font-semibold ${item.recommended || item.popular ? "pr-28" : ""}`}
                >
                  {item.name}
                </h3>
                <p className="mt-2 min-h-10 text-sm leading-5 text-muted-foreground">
                  {item.description || "Subscription plan from Monet."}
                </p>
                <div className="mt-5 flex flex-wrap items-center gap-3">
                  <div className="min-w-0">
                    <div className="whitespace-nowrap text-2xl font-semibold">
                      {formatMoney(item.pricePerConnector, currency)}
                    </div>
                    <p className="mt-1 text-xs text-muted-foreground">
                      per connector / month
                    </p>
                  </div>
                  <ContractDiscountCallout plan={item} />
                </div>
                <p className="mt-4 flex-1 text-sm font-medium">
                  {planLimit(item)}
                </p>
                <Button
                  className="mt-6"
                  disabled={!editable || busy}
                  variant={selectedPlanId === item.id ? "default" : "outline"}
                  onClick={() => selectPlan(item.id)}
                >
                  {selectedPlanId === item.id && pendingAction === "preview"
                    ? "Opening checkout…"
                    : "Go to checkout"}
                </Button>
              </div>
            </section>
          ))}
        </div>
      )}
      {plans.length > 0 && (
        <section className="panel overflow-hidden">
          <div className="border-b px-5 py-4">
            <h2 className="font-semibold">Compare plan features</h2>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full min-w-[680px] border-collapse text-sm">
              <thead>
                <tr className="border-b bg-muted/40 text-left">
                  <th scope="col" className="w-[48%] px-5 py-3 font-medium">
                    Feature
                  </th>
                  {plans.map((item) => (
                    <th
                      scope="col"
                      className="px-4 py-3 text-center font-semibold"
                      key={item.id}
                    >
                      <span className="block">{item.name}</span>
                      <span className="mt-1 block text-xs font-normal text-muted-foreground">
                        {formatMoney(item.pricePerConnector, currency)} / connector
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {planFeatureGroups.map((group) => (
                  <Fragment key={group.name}>
                    <tr className="border-b bg-muted/20">
                      <th
                        scope="rowgroup"
                        colSpan={plans.length + 1}
                        className="px-5 py-2.5 text-center text-xs font-semibold uppercase tracking-wide text-muted-foreground"
                      >
                        {group.name}
                      </th>
                    </tr>
                    {group.features.map((feature) => (
                      <tr className="border-b last:border-0" key={feature.name}>
                        <th scope="row" className="px-5 py-3 text-left font-normal">
                          {feature.name}
                        </th>
                        {plans.map((item) => {
                          const specifiedTier = item.tier >= 1 && item.tier <= 3;
                          const included = (
                            feature.tiers as readonly number[]
                          ).includes(item.tier);
                          return (
                            <td className="px-4 py-3 text-center" key={item.id}>
                              {included ? (
                                <span
                                  aria-label="Included"
                                  className="font-semibold text-success"
                                >
                                  ✓
                                </span>
                              ) : specifiedTier ? (
                                <span className="text-muted-foreground">—</span>
                              ) : (
                                <span className="text-muted-foreground">Not listed</span>
                              )}
                            </td>
                          );
                        })}
                      </tr>
                    ))}
                  </Fragment>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      )}

      {plan && (
        <Dialog
          open={checkoutDialogOpen}
          onOpenChange={setCheckoutDialogOpen}
        >
          <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-4xl">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div className="space-y-2">
                <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  Checkout
                </p>
                <DialogTitle>{plan.name}</DialogTitle>
                <DialogDescription>
                  Review the plan and invoice estimate before subscribing. No
                  payment is processed in this step.
                </DialogDescription>
              </div>
              <Button
                type="button"
                variant="outline"
                onClick={() => setCheckoutDialogOpen(false)}
              >
                Back to plans
              </Button>
            </div>

            {plan.maxConnectors === null && (
              <div className="border-y py-4">
                <Field
                  label="Connector quantity"
                  type="number"
                  min={1}
                  max={100000}
                  step={1}
                  value={connectorsDraft}
                  disabled={!editable || busy}
                  onChange={(event) => {
                    setConnectorsDraft(event.target.value);
                    setCheckoutPreview(null);
                    setPreviewBodyKey("");
                    setError("");
                  }}
                />
                <p className="mt-2 text-xs text-muted-foreground">
                  This plan has no connector limit. Enter the quantity confirmed
                  for this tenant to price the checkout.
                </p>
              </div>
            )}

            {connectorError && (
              <p role="alert" className="text-sm text-destructive">
                {connectorError}
              </p>
            )}
            {error && (
              <p role="alert" className="text-sm text-destructive">
                {error}
              </p>
            )}

            {checkoutPreview ? (
              <section className="rounded-lg border">
                <div className="border-b p-5">
                  <p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    Invoice preview
                  </p>
                  <h3 className="mt-1 text-xl font-semibold">
                    Subscription cost estimate
                  </h3>
                  <p className="mt-1 text-sm text-muted-foreground">
                    One-time setup fee only · {checkoutPreview.planName} ·{" "}
                    {checkoutPreview.maxConnectors} connectors
                  </p>
                </div>
                <div className="overflow-x-auto">
                  <table className="w-full min-w-[680px] border-collapse text-sm">
                    <thead>
                      <tr className="border-b bg-muted/30 text-left text-xs uppercase tracking-wide text-muted-foreground">
                        <th scope="col" className="px-5 py-3 font-medium">
                          Description
                        </th>
                        <th scope="col" className="px-4 py-3 font-medium">
                          Quantity
                        </th>
                        <th scope="col" className="px-4 py-3 font-medium">
                          Unit price
                        </th>
                        <th scope="col" className="px-5 py-3 text-right font-medium">
                          Amount
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {invoicePaymentSummary.map((item, index) => (
                        <tr className="border-b align-top" key={item.name + index}>
                          <td className="px-5 py-4">
                            <p className="font-medium">{item.name}</p>
                          </td>
                          <td className="px-4 py-4">1</td>
                          <td className="whitespace-nowrap px-4 py-4">
                            {item.isFree
                              ? "FOC"
                              : formatOneTimeAmount(item.amount, checkoutPreview.currency)}
                          </td>
                          <td className="whitespace-nowrap px-5 py-4 text-right font-medium">
                            {item.isFree
                              ? "FOC"
                              : formatOneTimeAmount(item.amount, checkoutPreview.currency)}
                          </td>
                        </tr>
                      ))}
                      {checkoutPreview.paymentSummary.length === 0 &&
                        checkoutPreview.setupFeeAmount > 0 && (
                          <tr className="border-b align-top">
                            <td className="px-5 py-4">
                              <p className="font-medium">One-time setup fee</p>
                            </td>
                            <td className="px-4 py-4">1</td>
                            <td className="whitespace-nowrap px-4 py-4">
                              {formatOneTimeAmount(
                                checkoutPreview.setupFeeAmount,
                                checkoutPreview.currency,
                              )}
                            </td>
                            <td className="whitespace-nowrap px-5 py-4 text-right font-medium">
                              {formatOneTimeAmount(
                                checkoutPreview.setupFeeAmount,
                                checkoutPreview.currency,
                              )}
                            </td>
                          </tr>
                        )}
                      {invoicePaymentSummary.length === 0 &&
                        checkoutPreview.setupFeeAmount === 0 && (
                          <tr className="border-b">
                            <td
                              colSpan={4}
                              className="px-5 py-4 text-sm text-muted-foreground"
                            >
                              No one-time setup fee is listed for this plan.
                            </td>
                          </tr>
                        )}
                    </tbody>
                  </table>
                </div>

                <div className="space-y-2 border-t bg-muted/10 p-5">
                  <div className="ml-auto flex max-w-md justify-between gap-6 text-sm">
                    <span className="text-muted-foreground">One-time total</span>
                    <span>
                      {formatOneTimeAmount(
                        checkoutPreview.totalAmount,
                        checkoutPreview.currency,
                      )}
                    </span>
                  </div>
                </div>
                {previewIsCurrent ? (
                  <DialogFooter className="border-t p-4">
                    <Button
                      disabled={!editable || busy}
                      onClick={() => void submitCreate()}
                    >
                      {pendingAction === "create" ? "Subscribing…" : "Subscribe"}
                    </Button>
                  </DialogFooter>
                ) : (
                  <div className="space-y-3 border-t p-4">
                    <p className="text-sm text-muted-foreground">
                      Update the checkout preview before subscribing.
                    </p>
                    <Button
                      disabled={!editable || !requestBody || busy}
                      onClick={() => void requestPreview()}
                    >
                      Refresh checkout preview
                    </Button>
                  </div>
                )}
              </section>
            ) : (
              <div className="space-y-3 border-t p-5">
                <p role="status" className="text-sm text-muted-foreground">
                  {pendingAction === "preview"
                    ? "Preparing checkout preview…"
                    : requestBody
                      ? "Review the checkout estimate before subscribing."
                      : "Enter a valid connector quantity to continue."}
                </p>
                <Button
                  disabled={!editable || !requestBody || busy || plansState !== "loaded"}
                  onClick={() => void requestPreview()}
                >
                  {pendingAction === "preview"
                    ? "Preparing checkout…"
                    : error
                      ? "Retry checkout preview"
                      : "Preview checkout"}
                </Button>
              </div>
            )}
          </DialogContent>
        </Dialog>
      )}

        </>
      )}
        </>
      )}

      <Dialog
        open={cancelDialogOpen}
        onOpenChange={(open) => {
          if (!cancelBusy) setCancelDialogOpen(open);
        }}
      >
        <DialogContent>
          <DialogTitle>Cancel this subscription?</DialogTitle>
          <DialogDescription>
            The subscription contract will be marked as cancelled. If it has a
            pending setup invoice, an admin may still need to handle that invoice
            separately.
          </DialogDescription>
          <DialogFooter>
            <Button
              variant="outline"
              disabled={cancelBusy}
              onClick={() => setCancelDialogOpen(false)}
            >
              Keep subscription
            </Button>
            <Button
              variant="destructive"
              disabled={!editable || cancelBusy || !canCancelCurrentSubscription}
              onClick={() => void submitCancelSubscription()}
            >
              {cancelBusy ? "Cancelling…" : "Confirm cancellation"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
