import React, { useEffect, useState } from 'react';
import { FaCoins } from 'react-icons/fa';

import { useAppStateContext } from '../context/user.data.context';
import { formatDateLabel } from '../utils/dateUtils';
import {
  FREE_PLAN_SUMMARY,
  Plan,
  PlanType,
  basePlans,
  freePlan,
  isOnFreePlan,
} from '../utils/plan';
import {
  cancelSubscription,
  paymentCheckout,
} from '../service/user/user.service';
import { Check } from '../components/ui/Check';
import { recomaze_ai_personalization_env } from '../env';
import { getBaseUrl } from '../utils/domain';
import Button from '../components/widgets/Button';
import VoucherRedeem from '../components/pricing/VoucherRedeem';
import { AppSumoPricing } from '../components/pricing/AppSumoPricing';
import { NormalPricing } from '../components/pricing/NormalPricing';
import { LAUNCH_DISCOUNT_PERCENT } from '../components/launch-discount/plans';
import { CreditHistoryTable } from '../components/billing/CreditHistoryTable';
import { CreditCostList } from '../components/billing/CreditCostList';
import InfoTooltip from '../components/agent-analytics/InfoTooltip';
import type { ICreditBalance } from '../service/credits/credits.interface';
import { getCreditBalance } from '../service/credits/credits.service';

const formatUSD = (amount: number) =>
  new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: amount % 1 === 0 ? 0 : 2,
  }).format(amount);

const Pricing = (): JSX.Element => {
  const { user, fetchUser, token, clientId } = useAppStateContext();

  const [liveCredits, setLiveCredits] = useState<ICreditBalance>({});

  useEffect(() => {
    if (!token) return;
    let cancelled = false;
    void (async () => {
      try {
        const balance = await getCreditBalance(token, clientId);
        if (!cancelled) setLiveCredits(balance);
      } catch {
        // Benign: credit balance unavailable for this store.
      }
    })();

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

  // The authoritative /v2/credits/balance endpoint wins over the user snapshot.
  const credits: ICreditBalance = {
    ...(user?.credits ?? {}),
    ...liveCredits,
  };
  const creditsGranted = credits.granted ?? 0;
  const creditsUsed = credits.used ?? 0;
  const creditsBalance =
    typeof credits.balance === 'number'
      ? credits.balance
      : Math.max(0, creditsGranted - creditsUsed);

  const [cancelOpen, setCancelOpen] = useState(false);
  const [cancelStep, setCancelStep] = useState<1 | 2>(1);
  const [cancelReason, setCancelReason] = useState<string>('');
  const [cancelFeedback, setCancelFeedback] = useState<string>('');
  const [cancelling, setCancelling] = useState(false);
  const [cancelError, setCancelError] = useState<string | null>(null);
  const [checkingOutKey, setCheckingOutKey] = useState<PlanType | null>(null);

  const plans = basePlans;

  const btnBase =
    'inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition ' +
    'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-black/30 focus-visible:ring-offset-2 ' +
    'disabled:opacity-50 disabled:cursor-not-allowed';
  const primaryBtn = `${btnBase} w-full bg-[#B7007C] text-white hover:bg-[#900063]`;
  const secondaryBtn = `${btnBase} w-full bg-white text-gray-900 ring-1 ring-gray-900/10 hover:bg-gray-900/5`;

  const isAppSumo = !!user?.is_app_sumo;

  const hasActiveSub = Boolean(user?.has_active_subscription);
  const isUserLoaded = !!user;

  const trialDaysLeft = Number.isFinite(user?.trial_days)
    ? (user?.trial_days as number)
    : 0;
  // App-side counter derived from the signup date. It grants no plan and no
  // extra credits, so it never means the merchant is on a paid tier. Only the
  // Stripe-native launch-discount trial below is a real trial.
  const hasTrialDaysLeft = trialDaysLeft > 0 && !hasActiveSub;

  const currentPlan = hasActiveSub
    ? plans.find(p => p.key === user?.plan_snapshot) || null
    : null;

  const billingLabel =
    user && user.plan_period_snapshot
      ? String(user.plan_period_snapshot).toUpperCase() === 'MONTHLY'
        ? 'Monthly'
        : 'Annual'
      : 'Monthly';

  const stripeStatusRaw = (user?.stripe_subscription_status || '')
    .toString()
    .toLowerCase();
  const isCanceled = stripeStatusRaw === 'canceled';
  // Live access decides it; plan_snapshot and the Stripe status persist after a
  // subscription dies, so a lapsed merchant is on Free and must read that way.
  const onFreePlan: boolean = isUserLoaded && isOnFreePlan(user);

  const bannerPlan: Plan | null = currentPlan ?? (onFreePlan ? freePlan : null);

  const launchDiscountEligible = user?.launch_discount_status === 'ELIGIBLE';
  const bannerMonthly = bannerPlan?.monthly || 0;
  const bannerDiscountedMonthly =
    Math.round(bannerMonthly * (1 - LAUNCH_DISCOUNT_PERCENT / 100) * 100) / 100;
  const autoRenew = user ? !user.stripe_cancel_at_period_end : null;
  const periodEndISO = user?.stripe_current_period_end || null;
  const accessUntilISO = user?.subscription_access_until || null;
  const remainingDays =
    typeof user?.subscription_remaining_days === 'number'
      ? user!.subscription_remaining_days
      : null;

  const previousPlan =
    plans.find(p => p.key === (user?.plan_snapshot as PlanType | undefined)) ||
    null;

  const tookLaunchDiscount = user?.launch_discount_status === 'USED';
  const launchTrial =
    tookLaunchDiscount && (stripeStatusRaw === 'trialing' || hasTrialDaysLeft);
  const launchPlan = currentPlan || previousPlan || bannerPlan;
  const launchMonthly = launchPlan?.monthly || 0;
  const launchFirstMonth =
    Math.round(launchMonthly * (1 - LAUNCH_DISCOUNT_PERCENT / 100) * 100) / 100;

  const statusTone = (s: string) => {
    switch (s) {
      case 'active':
        return 'bg-emerald-50 text-emerald-700 ring-emerald-600/20';
      case 'trialing':
        return 'bg-blue-50 text-blue-700 ring-blue-600/20';
      case 'past_due':
        return 'bg-amber-50 text-amber-700 ring-amber-600/20';
      case 'unpaid':
      case 'incomplete':
        return 'bg-red-50 text-red-700 ring-red-600/20';
      case 'canceled':
      case 'incomplete_expired':
        return 'bg-gray-100 text-gray-700 ring-gray-500/20';
      default:
        return 'bg-gray-50 text-gray-600 ring-gray-500/10';
    }
  };

  type CheckoutResponse = {
    success: boolean;
    message: string;
    session?: { id: string; url?: string };
  };

  const onInitializePayment = async (priceId: string, planKey: PlanType) => {
    try {
      setCheckingOutKey(planKey);

      const url = getBaseUrl(recomaze_ai_personalization_env?.wp_api_url);

      const res: CheckoutResponse = await paymentCheckout({
        price_id: priceId,
        cancel_url: `${url}/wp-admin/admin.php?page=recomaze#/agent-analytics`,
        success_url: `${url}/wp-admin/admin.php?page=recomaze#/agent-analytics`,
      });

      if (!res?.success || !res.session) {
        throw new Error(res?.message || 'Failed to create checkout session');
      }

      if (res.session.url) {
        window.location.replace(res.session.url);
        return;
      }

      throw new Error('No checkout URL returned');
    } catch (error) {
      console.error('payment error:', error);
    } finally {
      setCheckingOutKey(null);
    }
  };

  const handleCancelConfirm = async () => {
    if (!user?.subscription_id) return;
    try {
      setCancelling(true);
      setCancelError(null);

      const response = await cancelSubscription(user.subscription_id);

      if (response?.success) {
        await fetchUser();
      } else if (response?.message) {
        setCancelError(response.message);
      }
    } catch (e) {
      setCancelError(String(e));
    } finally {
      setCancelling(false);
      setCancelOpen(false);
      setCancelStep(1);
      setCancelReason('');
      setCancelFeedback('');
    }
  };

  const scrollToPlans = () => {
    const el = document.getElementById('plans-grid');
    if (el) el.scrollIntoView({ behavior: 'smooth' });
    setCancelOpen(false);
    setCancelStep(1);
  };

  return (
    <div className="mx-auto w-full max-w-[1600px] space-y-10 bg-white p-6 md:p-10">
      <header className="flex flex-col items-center justify-center text-center">
        <h1 className="text-2xl font-medium tracking-tight text-gray-900 md:text-3xl">
          Plans & Billing
        </h1>
        <p className="mt-2 text-sm text-gray-500">
          Monthly plans with tiered pricing based on your feature requirements.
        </p>
      </header>

      {launchTrial && hasTrialDaysLeft && (
        <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-5">
          <div className="flex items-start gap-4">
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-emerald-100">
              <span className="text-sm font-bold text-emerald-700">
                {trialDaysLeft}
              </span>
            </div>
            <div>
              <h3 className="text-sm font-medium text-emerald-900">
                {`Days left in your ${launchPlan?.name ?? 'plan'} trial`}
              </h3>
              <p className="mt-1 text-sm text-emerald-800">
                {`Full access now. When your trial ends you're charged ${formatUSD(
                  launchFirstMonth
                )} for your first month (${LAUNCH_DISCOUNT_PERCENT}% off), then ${formatUSD(
                  launchMonthly
                )}/mo. Cancel anytime.`}
              </p>
            </div>
          </div>
        </div>
      )}

      {(bannerPlan || isCanceled || launchTrial) && (
        <section className="overflow-hidden rounded-lg border border-gray-200 bg-white shadow-sm">
          {!isCanceled ? (
            <div className="flex flex-col border-b border-gray-100 p-6 md:flex-row md:items-center md:justify-between">
              <div className="space-y-1">
                <div className="flex items-center gap-3">
                  <h2 className="text-lg font-medium text-gray-900">
                    {launchTrial ? launchPlan?.name : bannerPlan?.name}
                  </h2>
                  <span className="inline-flex items-center rounded-md bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700 ring-1 ring-inset ring-gray-500/10">
                    {launchTrial
                      ? `Free Trial · ${LAUNCH_DISCOUNT_PERCENT}% off first month`
                      : 'Current Plan'}
                  </span>
                  {stripeStatusRaw && !hasTrialDaysLeft && (
                    <span
                      className={`inline-flex items-center rounded-md px-2.5 py-1 text-xs font-medium ring-1 ring-inset ${statusTone(stripeStatusRaw)}`}
                    >
                      {stripeStatusRaw.replace(/_/g, ' ')}
                    </span>
                  )}
                </div>
                <p className="text-sm text-gray-500">
                  {launchTrial
                    ? `${formatUSD(
                        launchFirstMonth
                      )} first month (${LAUNCH_DISCOUNT_PERCENT}% off), then ${formatUSD(
                        launchMonthly
                      )}/mo after your trial.`
                    : onFreePlan
                      ? FREE_PLAN_SUMMARY
                      : `${formatUSD(bannerMonthly)}/mo — You can change plans at any time.`}
                </p>
                {!launchTrial &&
                  !hasTrialDaysLeft &&
                  !onFreePlan &&
                  launchDiscountEligible &&
                  bannerPlan && (
                    <p className="text-sm font-medium text-emerald-700">
                      First month {formatUSD(bannerDiscountedMonthly)} (
                      {LAUNCH_DISCOUNT_PERCENT}% off)
                    </p>
                  )}
              </div>

              <div className="mt-4 flex items-center gap-3 md:mt-0">
                <Button
                  variant="secondary"
                  onClick={() => {
                    setCancelOpen(true);
                    setCancelStep(1);
                  }}
                  disabled={!hasActiveSub}
                  className="rounded-md border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-red-600 transition-colors hover:bg-red-50 disabled:cursor-not-allowed disabled:border-gray-200 disabled:bg-gray-100 disabled:text-gray-400 disabled:opacity-100"
                >
                  Cancel Plan
                </Button>
              </div>
            </div>
          ) : (
            <div className="flex flex-col border-b border-gray-100 bg-gray-50 p-6 md:flex-row md:items-center md:justify-between">
              <div className="space-y-1">
                <div className="flex items-center gap-3">
                  <h2 className="text-lg font-medium text-gray-900">
                    {previousPlan?.name || 'No active plan'}
                  </h2>
                  <span className="inline-flex items-center rounded-md bg-gray-200 px-2.5 py-1 text-xs font-medium text-gray-700 ring-1 ring-inset ring-gray-500/20">
                    Canceled
                  </span>
                </div>
                <p className="text-sm text-gray-500">
                  {formatDateLabel(accessUntilISO)
                    ? `You have access until ${formatDateLabel(accessUntilISO)}.`
                    : 'Your billing has been stopped.'}
                </p>
              </div>

              <div className="mt-4 flex items-center gap-3 md:mt-0">
                {previousPlan && !previousPlan.enterprise && (
                  <Button
                    onClick={() =>
                      onInitializePayment(
                        previousPlan.priceId,
                        previousPlan.key
                      )
                    }
                    className="rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-gray-800"
                  >
                    Reactivate {previousPlan.name}
                  </Button>
                )}
                <Button
                  variant="secondary"
                  onClick={scrollToPlans}
                  className="rounded-md border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50"
                >
                  View Plans
                </Button>
              </div>
            </div>
          )}

          {!hasTrialDaysLeft && !onFreePlan && (
            <div className="bg-gray-50/50 p-6">
              <div className="grid grid-cols-2 gap-x-6 gap-y-6 sm:grid-cols-3 lg:grid-cols-5">
                <div>
                  <dt className="text-xs font-medium text-gray-500">
                    Billing Period
                  </dt>
                  <dd className="mt-1 text-sm font-medium text-gray-900">
                    {billingLabel}
                  </dd>
                </div>
                <div>
                  <dt className="text-xs font-medium text-gray-500">
                    Auto-renew
                  </dt>
                  <dd className="mt-1 text-sm font-medium text-gray-900">
                    {autoRenew === null
                      ? '-'
                      : autoRenew
                        ? 'Active'
                        : 'Disabled'}
                  </dd>
                </div>
                <div>
                  <dt className="text-xs font-medium text-gray-500">
                    Current Period Ends
                  </dt>
                  <dd className="mt-1 text-sm font-medium text-gray-900">
                    {formatDateLabel(periodEndISO) || '-'}
                  </dd>
                </div>
                <div>
                  <dt className="text-xs font-medium text-gray-500">
                    Remaining Days
                  </dt>
                  <dd className="mt-1 text-sm font-medium text-gray-900">
                    {remainingDays ?? '-'}
                  </dd>
                </div>
                <div>
                  <dt className="text-xs font-medium text-gray-500">
                    Access Until
                  </dt>
                  <dd className="mt-1 text-sm font-medium text-gray-900">
                    {formatDateLabel(accessUntilISO) || '-'}
                  </dd>
                </div>
              </div>

              {user?.stripe_cancel_at_period_end && !isCanceled && (
                <div className="mt-6 flex items-center gap-2 rounded-md bg-amber-50 p-3 text-sm text-amber-800 ring-1 ring-inset ring-amber-600/20">
                  <svg
                    className="h-4 w-4 shrink-0 text-amber-600"
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fillRule="evenodd"
                      d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z"
                      clipRule="evenodd"
                    />
                  </svg>
                  Your subscription is scheduled to cancel at the end of the
                  current billing period.
                </div>
              )}
              {cancelError && (
                <div className="mt-6 rounded-md bg-red-50 p-4 text-sm text-red-800 ring-1 ring-inset ring-red-600/20">
                  <h4 className="font-semibold text-red-900">
                    Cancellation failed
                  </h4>
                  <p className="mt-1">{cancelError}</p>
                </div>
              )}
            </div>
          )}
        </section>
      )}

      <VoucherRedeem />

      {/* AppSumo lifetime deal OR regular plan grid */}
      {isAppSumo ? (
        <AppSumoPricing />
      ) : (
        <NormalPricing
          user={user}
          isUserLoaded={isUserLoaded}
          hasActiveSub={hasActiveSub}
          isOnFreePlan={onFreePlan}
          isCanceled={isCanceled}
          launchTrial={launchTrial}
          currentPlan={currentPlan}
          billingLabel={billingLabel}
          checkingOutKey={checkingOutKey}
          onInitializePayment={onInitializePayment}
          primaryBtn={primaryBtn}
          secondaryBtn={secondaryBtn}
        />
      )}

      {/* Credit balance + history */}
      {token && (
        <div className="space-y-6">
          <section className="rounded-2xl border border-gray-200 bg-white p-6">
            <div className="flex items-center gap-2">
              <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-amber-50 ring-1 ring-amber-100">
                <FaCoins className="h-4 w-4 text-amber-500" />
              </span>
              <h2 className="text-base font-semibold text-gray-900">
                Credit balance
              </h2>
            </div>
            <div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-3">
              <CreditStat
                label="Remaining"
                value={creditsBalance}
                tooltip="Credits available to spend right now. Actions like content generation and scans draw from this balance."
                highlight
              />
              <CreditStat
                label="Used"
                value={creditsUsed}
                tooltip="Credits spent since your plan last refilled. Resets to zero when your plan renews each month."
              />
              <CreditStat
                label="Granted"
                value={creditsGranted}
                tooltip="Total credits added to your account this period, based on your plan's monthly allowance."
              />
            </div>
            <div className="mt-4 h-1.5 w-full overflow-hidden rounded-full bg-gray-100">
              <div
                className="h-full bg-gradient-to-r from-amber-400 to-orange-400 transition-all duration-700"
                style={{
                  width: `${Math.round(
                    Math.min(
                      1,
                      Math.max(0, creditsUsed / Math.max(1, creditsGranted))
                    ) * 100
                  )}%`,
                }}
              />
            </div>
          </section>

          <CreditCostList />

          <CreditHistoryTable token={token} clientId={clientId} />
        </div>
      )}

      <section className="rounded-lg border border-gray-200 bg-white shadow-sm">
        <header className="border-b border-gray-100 bg-gray-50/50 px-6 py-4">
          <h3 className="text-sm font-medium text-gray-900">
            How billing works when you switch plans
          </h3>
        </header>
        <div className="grid grid-cols-1 divide-y divide-gray-100 md:grid-cols-2 md:divide-x md:divide-y-0">
          <div className="p-6 space-y-4">
            <span className="inline-flex items-center rounded-md bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-800 ring-1 ring-inset ring-gray-500/10">
              Upgrading Plans
            </span>
            <div className="space-y-2 text-sm text-gray-600">
              <p>
                Moving to a higher plan? You only pay the{' '}
                <strong className="font-medium text-gray-900">
                  prorated difference
                </strong>{' '}
                for the days remaining in your current billing cycle.
              </p>
              <div className="rounded-md bg-gray-50 p-3 text-xs">
                <span className="font-medium text-gray-900">Example:</span> Fast
                Growing ($39/mo) → Scaling ($99/mo) at mid-cycle = $39 + ($99 −
                $39) × (15/30) ={' '}
                <strong className="font-medium text-gray-900">
                  $69 charge
                </strong>
                .
              </div>
            </div>
          </div>
          <div className="p-6 space-y-4">
            <span className="inline-flex items-center rounded-md bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-800 ring-1 ring-inset ring-gray-500/10">
              Downgrading Plans
            </span>
            <div className="space-y-2 text-sm text-gray-600">
              <p>
                Moving to a lower plan? We apply an{' '}
                <strong className="font-medium text-gray-900">
                  account credit
                </strong>{' '}
                for the unused portion of your current cycle toward future
                charges.
              </p>
              <div className="rounded-md bg-gray-50 p-3 text-xs">
                <span className="font-medium text-gray-900">Example:</span>{' '}
                Scaling ($99/mo) → Fast Growing ($39/mo) at mid-cycle = ($99 −
                $39) × (15/30) ={' '}
                <strong className="font-medium text-gray-900">
                  $30 credit
                </strong>
                .
              </div>
            </div>
          </div>
        </div>
      </section>

      {cancelOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div
            className="fixed inset-0 bg-gray-900/40 backdrop-blur-sm transition-opacity"
            onClick={() => !cancelling && setCancelOpen(false)}
          />
          <div className="relative z-10 w-full max-w-md overflow-hidden rounded-xl bg-white shadow-2xl ring-1 ring-gray-200">
            {cancelStep === 1 ? (
              <div className="p-6">
                <h3 className="text-lg font-medium text-gray-900">
                  Cancel Subscription
                </h3>
                <p className="mt-2 text-sm text-gray-500">
                  Before you cancel, here is what will happen to your account:
                </p>

                <ul className="mt-5 space-y-3">
                  <li className="flex items-start gap-3 text-sm text-gray-600">
                    <Check className="mt-0.5 h-4 w-4 shrink-0 text-gray-900" />
                    <span>
                      Keep access to all features until{' '}
                      <strong className="font-medium text-gray-900">
                        {formatDateLabel(periodEndISO) ||
                          'the end of your billing cycle'}
                      </strong>
                      .
                    </span>
                  </li>
                  <li className="flex items-start gap-3 text-sm text-gray-600">
                    <Check className="mt-0.5 h-4 w-4 shrink-0 text-gray-900" />
                    <span>
                      You can switch to a lower-cost plan anytime instead of
                      canceling completely.
                    </span>
                  </li>
                </ul>

                <div className="mt-6 border-t border-gray-100 pt-6">
                  <label className="block text-sm font-medium text-gray-900">
                    Optional: Why are you leaving?
                  </label>
                  <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
                    {[
                      'Too expensive',
                      'Not seeing value',
                      'Temporary pause',
                      'Switching tools',
                    ].map(r => (
                      <label
                        key={r}
                        className="flex cursor-pointer items-center gap-2 rounded-md border border-gray-200 p-3 text-sm hover:bg-gray-50"
                      >
                        <input
                          type="radio"
                          name="cancel-reason"
                          value={r}
                          checked={cancelReason === r}
                          onChange={e => setCancelReason(e.target.value)}
                          className="h-4 w-4 border-gray-300 text-gray-900 focus:ring-gray-900"
                        />
                        <span className="text-gray-700">{r}</span>
                      </label>
                    ))}
                  </div>
                  <textarea
                    value={cancelFeedback}
                    onChange={e => setCancelFeedback(e.target.value)}
                    placeholder="Other feedback..."
                    className="mt-3 w-full rounded-md border border-gray-200 px-3 py-2 text-sm text-gray-900 focus:border-gray-900 focus:outline-none focus:ring-1 focus:ring-gray-900"
                    rows={2}
                  />
                </div>

                <div className="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
                  <Button
                    variant="secondary"
                    className="w-full justify-center rounded-md border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50 disabled:bg-gray-100 disabled:text-gray-400 disabled:border-gray-200 sm:w-auto"
                    onClick={() => {
                      setCancelOpen(false);
                      setCancelStep(1);
                    }}
                    disabled={cancelling}
                  >
                    Keep Plan
                  </Button>
                  <Button
                    className="w-full justify-center rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:bg-gray-100 disabled:text-gray-400 disabled:border-gray-200 sm:w-auto"
                    onClick={() => setCancelStep(2)}
                    disabled={cancelling}
                  >
                    Continue to Cancel
                  </Button>
                </div>
              </div>
            ) : (
              <div className="p-6">
                <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
                  <svg
                    className="h-6 w-6 text-red-600"
                    fill="none"
                    viewBox="0 0 24 24"
                    strokeWidth="1.5"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                    />
                  </svg>
                </div>
                <h3 className="text-center text-lg font-medium text-gray-900">
                  Confirm Cancellation
                </h3>
                <p className="mt-2 text-center text-sm text-gray-500">
                  Are you sure you want to cancel? You will lose access to
                  premium features on{' '}
                  <strong className="font-medium text-gray-900">
                    {formatDateLabel(periodEndISO) ||
                      'the end of your current period'}
                  </strong>
                  .
                </p>

                <div className="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:justify-between">
                  <Button
                    variant="secondary"
                    className="w-full justify-center rounded-md border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-50 disabled:bg-gray-100 disabled:text-gray-400 disabled:border-gray-200 sm:w-auto"
                    onClick={() => setCancelStep(1)}
                    disabled={cancelling}
                  >
                    Back
                  </Button>
                  <Button
                    className="w-full justify-center rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:bg-gray-100 disabled:text-gray-400 disabled:border-gray-200 sm:w-auto"
                    onClick={handleCancelConfirm}
                    disabled={!hasActiveSub || cancelling}
                  >
                    {cancelling ? 'Cancelling…' : 'Yes, Cancel Plan'}
                  </Button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

function CreditStat({
  label,
  value,
  highlight,
  tooltip,
}: {
  label: string;
  value: number;
  highlight?: boolean;
  tooltip?: string;
}) {
  return (
    <div className="rounded-xl border border-gray-200 bg-gray-50/60 px-4 py-3">
      <p className="flex items-center text-xs font-medium uppercase tracking-wide text-gray-500">
        {label}
        {tooltip && <InfoTooltip text={tooltip} />}
      </p>
      <p
        className={`mt-1 text-2xl font-semibold tabular-nums ${
          highlight ? 'text-[#B7007C]' : 'text-gray-900'
        }`}
      >
        {value.toLocaleString()}
      </p>
    </div>
  );
}

export default Pricing;
