'use client';

import { useState, useEffect, useCallback, use } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Save, ToggleLeft, ToggleRight, Check, DollarSign, Loader2, AlertCircle, Plus, Trash2 } from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { getAdminBillingPlan, createAdminBillingPlan, updateAdminBillingPlan, getAdminPlanPrices, upsertAdminPlanPrice, getAdminGatewaySettings } from '@client/api/admin';
import { toast } from 'sonner';
import { PLAN_OVERRIDE_CURRENCIES } from '@/shared/billingCurrencies';

function getAllFeatures(t: (k: string, f: string) => string) {
  return [
    { key: 'voice_agent', label: t('billing.features.voiceAgent', 'Voice Agent'), desc: t('billing.features.voiceAgentDesc', 'AI-powered phone call handling') },
    { key: 'chat_agent', label: t('billing.features.chatAgent', 'Chat Agent'), desc: t('billing.features.chatAgentDesc', 'Web chat and messaging') },
    { key: 'whatsapp_agent', label: t('billing.features.whatsappAgent', 'WhatsApp Agent'), desc: t('billing.features.whatsappAgentDesc', 'WhatsApp Business inbound + outbound via Meta Cloud API') },
    { key: 'storefront', label: t('billing.features.storefront', 'QR Storefront'), desc: t('billing.features.storefrontDesc', 'Per-table QR codes & customer-facing storefront for dine-in / takeaway') },
    { key: 'multi_branch', label: t('billing.features.multiBranch', 'Multi-Branch'), desc: t('billing.features.multiBranchDesc', 'Multiple location support') },
    { key: 'analytics', label: t('billing.features.analytics', 'Advanced Analytics'), desc: t('billing.features.analyticsDesc', 'Detailed reports and insights') },
    { key: 'knowledge_base', label: t('billing.features.knowledgeBase', 'Knowledge Base'), desc: t('billing.features.knowledgeBaseDesc', 'Custom AI knowledge sources') },
    { key: 'bulk_upload', label: t('billing.features.bulkUpload', 'Bulk Menu Upload'), desc: t('billing.features.bulkUploadDesc', 'AI-powered menu import') },
    { key: 'priority_support', label: t('billing.features.prioritySupport', 'Priority Support'), desc: t('billing.features.prioritySupportDesc', '24/7 dedicated support') },
    { key: 'loyalty', label: t('billing.features.loyalty', 'Loyalty Program'), desc: t('billing.features.loyaltyDesc', 'Points, rewards, and customer loyalty tiers') },
    { key: 'marketing', label: t('billing.features.marketing', 'Marketing'), desc: t('billing.features.marketingDesc', 'Audiences and outbound campaigns') },
    { key: 'gift_cards', label: t('billing.features.giftCards', 'Gift Cards'), desc: t('billing.features.giftCardsDesc', 'Sell and redeem digital gift cards') },
    { key: 'coupons', label: t('billing.features.coupons', 'Coupons'), desc: t('billing.features.couponsDesc', 'Discount codes and promotions') },
  ];
}

const DEFAULT_FORM = {
  name: '',
  description: '',
  priceMonthly: '',
  priceAnnual: '',
  trialDays: '0',
  active: true,
  features: [] as string[],
  limits: {
    conversations_per_month: '',
    api_calls_per_minute: '',
    concurrent_voice_calls: '',
    max_branches: '',
  },
};

type FormType = typeof DEFAULT_FORM;

interface PlanPrice {
  id: string;
  currencyCode: string;
  priceMonthly: number;
  priceAnnual: number;
}

// USD is the default (set via the main Price (USD) fields above) and INR is
// managed in its own Razorpay-specific section, so neither appears here.
// Shared constant lives in `src/shared/billingCurrencies.ts`.
const SUPPORTED_CURRENCIES = PLAN_OVERRIDE_CURRENCIES;

export default function PlanFormPage({ params }: { params: Promise<{ id?: string }> }) {
  const { t } = useLanguage();
  const router = useRouter();
  const resolvedParams = use(params);
  const planId = resolvedParams?.id;
  const isNew = !planId || planId === 'new';
  const allFeatures = getAllFeatures(t);

  usePageHeader(
    isNew ? t('billing.addPlan', 'Add Plan') : t('billing.editPlan', 'Edit Plan'),
    t('billing.planDescription', 'Configure subscription plan details and features')
  );

  const [form, setForm] = useState<FormType>(DEFAULT_FORM);
  const [loading, setLoading] = useState(!isNew);
  const [saving, setSaving] = useState(false);
  const [stripeSkippedWarning, setStripeSkippedWarning] = useState(false);

  const [planPrices, setPlanPrices] = useState<PlanPrice[]>([]);
  const [pricesLoading, setPricesLoading] = useState(false);
  const [addingCurrency, setAddingCurrency] = useState('');
  const [newPriceMonthly, setNewPriceMonthly] = useState('');
  const [newPriceAnnual, setNewPriceAnnual] = useState('');
  const [savingPrice, setSavingPrice] = useState(false);

  const [razorpayActive, setRazorpayActive] = useState(false);
  const [inrMonthly, setInrMonthly] = useState('');
  const [inrAnnual, setInrAnnual] = useState('');
  const [savingInr, setSavingInr] = useState(false);

  useEffect(() => {
    if (isNew) return;
    getAdminBillingPlan(planId!)
      .then((res: { plan: {
        name: string; description: string; priceMonthly: number; priceAnnual: number;
        trialDays: number; isActive: boolean; features: string[];
        limits: Record<string, unknown>;
      } }) => {
        const p = res.plan;
        const lim = p.limits ?? {};
        setForm({
          name: p.name ?? '',
          description: p.description ?? '',
          priceMonthly: p.priceMonthly > 0 ? String(p.priceMonthly) : '',
          priceAnnual: p.priceAnnual > 0 ? String(p.priceAnnual) : '',
          trialDays: String(p.trialDays ?? 14),
          active: p.isActive !== false,
          features: Array.isArray(p.features) ? p.features : [],
          limits: {
            conversations_per_month: lim.conversations_per_month != null ? String(lim.conversations_per_month) : '',
            api_calls_per_minute: lim.api_calls_per_minute != null ? String(lim.api_calls_per_minute) : '',
            concurrent_voice_calls: lim.concurrent_voice_calls != null ? String(lim.concurrent_voice_calls) : '',
            max_branches: lim.max_branches != null ? String(lim.max_branches) : '',
          },
        });
      })
      .catch(() => toast.error('Failed to load plan'))
      .finally(() => setLoading(false));
  }, [isNew, planId]);

  useEffect(() => {
    if (isNew || !planId) return;
    setPricesLoading(true);
    getAdminPlanPrices(planId)
      .then((res: { prices: PlanPrice[] }) => {
        const prices = res.prices ?? [];
        setPlanPrices(prices);
        const inr = prices.find(p => p.currencyCode === 'INR');
        if (inr) {
          setInrMonthly(inr.priceMonthly > 0 ? String(inr.priceMonthly) : '');
          setInrAnnual(inr.priceAnnual > 0 ? String(inr.priceAnnual) : '');
        }
      })
      .catch(() => {})
      .finally(() => setPricesLoading(false));
  }, [isNew, planId]);

  useEffect(() => {
    getAdminGatewaySettings()
      .then((res: { settings: { razorpay_active?: boolean } }) => {
        setRazorpayActive(Boolean(res.settings?.razorpay_active));
      })
      .catch(() => {});
  }, []);

  const toggleFeature = useCallback((key: string) => {
    setForm(f => ({
      ...f,
      features: f.features.includes(key) ? f.features.filter(k => k !== key) : [...f.features, key],
    }));
  }, []);

  const buildLimits = useCallback((lim: typeof DEFAULT_FORM.limits) => {
    const result: Record<string, number> = {};
    if (lim.conversations_per_month !== '') result.conversations_per_month = parseInt(lim.conversations_per_month, 10) || 0;
    if (lim.api_calls_per_minute !== '') result.api_calls_per_minute = parseInt(lim.api_calls_per_minute, 10) || 0;
    if (lim.concurrent_voice_calls !== '') result.concurrent_voice_calls = parseInt(lim.concurrent_voice_calls, 10) || 0;
    if (lim.max_branches !== '') result.max_branches = parseInt(lim.max_branches, 10) || 0;
    return result;
  }, []);

  const handleSave = useCallback(async () => {
    if (!form.name.trim()) { toast.error('Plan name is required'); return; }
    if (!form.priceMonthly && parseFloat(form.priceMonthly) !== 0) { toast.error('Monthly price is required'); return; }

    setSaving(true);
    setStripeSkippedWarning(false);
    const payload = {
      name: form.name.trim(),
      description: form.description.trim(),
      priceMonthly: parseFloat(form.priceMonthly) || 0,
      priceAnnual: parseFloat(form.priceAnnual) || 0,
      trialDays: parseInt(form.trialDays, 10) || 14,
      isActive: form.active,
      features: form.features,
      limits: buildLimits(form.limits),
    };

    try {
      const res: { stripeSkipped?: boolean } = isNew
        ? await createAdminBillingPlan(payload)
        : await updateAdminBillingPlan(planId!, payload);

      if (res.stripeSkipped) {
        setStripeSkippedWarning(true);
        toast.success(`Plan ${isNew ? 'created' : 'saved'} (Stripe not configured — price not synced)`);
      } else {
        toast.success(`Plan ${isNew ? 'created' : 'saved'} and synced with Stripe`);
      }
      router.push('/admin/billing');
    } catch {
      toast.error(`Failed to ${isNew ? 'create' : 'save'} plan`);
    }
    setSaving(false);
  }, [form, isNew, planId, buildLimits, router]);

  const handleSaveInr = useCallback(async () => {
    if (!planId) return;
    const m = parseFloat(inrMonthly) || 0;
    const a = parseFloat(inrAnnual) || 0;
    if (m <= 0) { toast.error('Monthly INR price is required'); return; }
    setSavingInr(true);
    try {
      await upsertAdminPlanPrice(planId, 'INR', m, a);
      setPlanPrices(prev => {
        const idx = prev.findIndex(p => p.currencyCode === 'INR');
        const entry: PlanPrice = { id: 'INR', currencyCode: 'INR', priceMonthly: m, priceAnnual: a };
        if (idx >= 0) { const copy = [...prev]; copy[idx] = entry; return copy; }
        return [...prev, entry];
      });
      toast.success('INR pricing saved');
    } catch {
      toast.error('Failed to save INR pricing');
    }
    setSavingInr(false);
  }, [planId, inrMonthly, inrAnnual]);

  const handleAddPrice = useCallback(async () => {
    if (!addingCurrency || !newPriceMonthly) {
      toast.error('Currency and monthly price are required');
      return;
    }
    setSavingPrice(true);
    try {
      await upsertAdminPlanPrice(planId!, addingCurrency, parseFloat(newPriceMonthly) || 0, parseFloat(newPriceAnnual) || 0);
      toast.success(`${addingCurrency} pricing saved`);
      setPlanPrices(prev => {
        const existing = prev.findIndex(p => p.currencyCode === addingCurrency);
        const newEntry: PlanPrice = { id: addingCurrency, currencyCode: addingCurrency, priceMonthly: parseFloat(newPriceMonthly) || 0, priceAnnual: parseFloat(newPriceAnnual) || 0 };
        if (existing >= 0) { const copy = [...prev]; copy[existing] = newEntry; return copy; }
        return [...prev, newEntry];
      });
      setAddingCurrency('');
      setNewPriceMonthly('');
      setNewPriceAnnual('');
    } catch {
      toast.error('Failed to save currency pricing');
    }
    setSavingPrice(false);
  }, [addingCurrency, newPriceMonthly, newPriceAnnual, planId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="animate-spin" size={32} />
      </div>
    );
  }

  return (
    <>
      <div className="flex items-center gap-3 mb-6">
        <Link href="/admin/billing" className="btn-ghost p-1.5"><ArrowLeft size={16} /></Link>
        <h2 className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>
          {isNew ? t('billing.addNewPlan', 'Add New Plan') : t('billing.editPlan', 'Edit Plan')}
        </h2>
        <div className="ml-auto flex gap-2">
          <Link href="/admin/billing" className="btn-secondary">{t('common.cancel', 'Cancel')}</Link>
          <button className="btn-primary" onClick={handleSave} disabled={saving}>
            {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
            {isNew ? t('billing.createPlan', 'Create Plan') : t('billing.saveChanges', 'Save Changes')}
          </button>
        </div>
      </div>

      {stripeSkippedWarning && (
        <div className="flex items-center gap-2 p-3 rounded-lg mb-5 text-sm" style={{ backgroundColor: 'hsl(var(--warning) / 0.1)', color: 'hsl(var(--warning))' }}>
          <AlertCircle size={15} />
          Stripe is not configured — plan saved to DB only. Set STRIPE_SECRET_KEY to enable price syncing.
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <div className="lg:col-span-2 space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.planDetails', 'Plan Details')}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('billing.planName', 'Plan Name')} *</label>
                <input className="input-base" placeholder="e.g. Starter, Growth, Enterprise" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} required />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Description</label>
                <input className="input-base" placeholder="Short plan description" value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('billing.priceUsd', 'Monthly Price (USD)')} *</label>
                <div className="relative">
                  <DollarSign size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <input type="number" min="0" step="0.01" className="input-base pl-9" placeholder="49" value={form.priceMonthly} onChange={e => setForm(f => ({ ...f, priceMonthly: e.target.value }))} required />
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Annual Price (USD) <span className="font-normal opacity-60">optional</span></label>
                <div className="relative">
                  <DollarSign size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                  <input type="number" min="0" step="0.01" className="input-base pl-9" placeholder="490 (save ~17%)" value={form.priceAnnual} onChange={e => setForm(f => ({ ...f, priceAnnual: e.target.value }))} />
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Trial Days</label>
                <input type="number" min="0" max="365" className="input-base" placeholder="14" value={form.trialDays} onChange={e => setForm(f => ({ ...f, trialDays: e.target.value }))} />
              </div>
            </div>
          </div>

          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>Rate Limits <span className="text-xs font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>(leave blank = unlimited)</span></h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {[
                { key: 'conversations_per_month' as const, label: 'Conversations / month', placeholder: 'e.g. 500' },
                { key: 'api_calls_per_minute' as const, label: 'API calls / minute', placeholder: 'e.g. 60' },
                { key: 'concurrent_voice_calls' as const, label: 'Concurrent voice calls', placeholder: 'e.g. 5' },
                { key: 'max_branches' as const, label: 'Max branches', placeholder: 'e.g. 3' },
              ].map(limit => (
                <div key={limit.key}>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{limit.label}</label>
                  <input
                    type="number"
                    min="0"
                    className="input-base"
                    placeholder={limit.placeholder}
                    value={form.limits[limit.key]}
                    onChange={e => setForm(f => ({ ...f, limits: { ...f.limits, [limit.key]: e.target.value } }))}
                  />
                </div>
              ))}
            </div>
          </div>

          <div className="card p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.featuresIncluded', 'Features Included')}</h3>
              <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{allFeatures.filter(f => form.features.includes(f.key)).length} of {allFeatures.length} enabled</span>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {allFeatures.map(feat => {
                const enabled = form.features.includes(feat.key);
                return (
                  <div
                    key={feat.key}
                    className="flex items-center justify-between p-3 rounded-xl border cursor-pointer transition-all"
                    style={{
                      borderColor: enabled ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                      backgroundColor: enabled ? 'hsl(var(--primary-light))' : 'hsl(var(--surface))',
                    }}
                    onClick={() => toggleFeature(feat.key)}
                  >
                    <div>
                      <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{feat.label}</p>
                      <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{feat.desc}</p>
                    </div>
                    <div className="w-5 h-5 rounded border-2 flex items-center justify-center shrink-0"
                      style={{ borderColor: enabled ? 'hsl(var(--primary))' : 'hsl(var(--border))', backgroundColor: enabled ? 'hsl(var(--primary))' : 'transparent' }}>
                      {enabled && <Check size={10} className="text-white" />}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {!isNew && razorpayActive && (
            <div className="card p-5">
              <div className="flex items-center gap-2 mb-1">
                <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>Price (INR) — Razorpay</h3>
                <span className="badge badge-neutral text-xs">For Indian customers</span>
              </div>
              <p className="text-xs mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
                Razorpay is enabled. Set INR pricing for this plan; it will be used for Indian customers checking out via Razorpay.
              </p>
              <div className="grid grid-cols-3 gap-3 items-end">
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Monthly (₹) *</label>
                  <input type="number" min="0" step="1" className="input-base" placeholder="e.g. 999" value={inrMonthly} onChange={e => setInrMonthly(e.target.value)} />
                </div>
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Annual (₹) <span className="font-normal opacity-60">optional</span></label>
                  <input type="number" min="0" step="1" className="input-base" placeholder="e.g. 9990" value={inrAnnual} onChange={e => setInrAnnual(e.target.value)} />
                </div>
                <button
                  className="btn-primary flex items-center justify-center gap-1"
                  onClick={handleSaveInr}
                  disabled={savingInr || pricesLoading}
                >
                  {savingInr ? <Loader2 size={13} className="animate-spin" /> : <Save size={13} />}
                  Save INR
                </button>
              </div>
            </div>
          )}

          {!isNew && (
            <div className="card p-5">
              <h3 className="font-semibold mb-1" style={{ color: 'hsl(var(--foreground))' }}>Per-Currency Pricing</h3>
              <p className="text-xs mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
                Override prices for specific non-USD currencies. USD uses the prices above; INR is managed in the Razorpay section.
              </p>
              {pricesLoading ? (
                <div className="flex items-center gap-2 py-4" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Loader2 size={14} className="animate-spin" /> Loading…
                </div>
              ) : (
                <>
                  {planPrices.filter(pp => !(razorpayActive && pp.currencyCode === 'INR')).length > 0 && (
                    <div className="mb-4 space-y-2">
                      {planPrices.filter(pp => !(razorpayActive && pp.currencyCode === 'INR')).map(pp => (
                        <div key={pp.currencyCode} className="flex items-center justify-between px-3 py-2 rounded-lg text-sm" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                          <span className="font-semibold w-14" style={{ color: 'hsl(var(--foreground))' }}>{pp.currencyCode}</span>
                          <span style={{ color: 'hsl(var(--muted-foreground))' }}>{pp.priceMonthly}/mo</span>
                          <span style={{ color: 'hsl(var(--muted-foreground))' }}>{pp.priceAnnual}/yr</span>
                          <button
                            className="text-xs font-medium"
                            style={{ color: 'hsl(var(--primary))' }}
                            onClick={() => {
                              setAddingCurrency(pp.currencyCode);
                              setNewPriceMonthly(String(pp.priceMonthly));
                              setNewPriceAnnual(String(pp.priceAnnual));
                            }}
                          >
                            Edit
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                  <div className="grid grid-cols-4 gap-2 items-end">
                    <div>
                      <label className="block text-xs font-semibold mb-1" style={{ color: 'hsl(var(--foreground-secondary))' }}>Currency</label>
                      <select
                        className="input-base"
                        value={addingCurrency}
                        onChange={e => setAddingCurrency(e.target.value)}
                      >
                        <option value="">Select…</option>
                        {SUPPORTED_CURRENCIES.map(c => (
                          <option key={c} value={c}>{c}</option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="block text-xs font-semibold mb-1" style={{ color: 'hsl(var(--foreground-secondary))' }}>Monthly</label>
                      <input type="number" min="0" step="0.01" className="input-base" placeholder="0.00" value={newPriceMonthly} onChange={e => setNewPriceMonthly(e.target.value)} />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold mb-1" style={{ color: 'hsl(var(--foreground-secondary))' }}>Annual</label>
                      <input type="number" min="0" step="0.01" className="input-base" placeholder="0.00" value={newPriceAnnual} onChange={e => setNewPriceAnnual(e.target.value)} />
                    </div>
                    <button
                      className="btn-primary flex items-center gap-1"
                      onClick={handleAddPrice}
                      disabled={savingPrice || !addingCurrency}
                    >
                      {savingPrice ? <Loader2 size={13} className="animate-spin" /> : <Plus size={13} />}
                      Save
                    </button>
                  </div>
                </>
              )}
            </div>
          )}
        </div>

        <div className="space-y-5">
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.planStatus', 'Plan Status')}</h3>
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.activePlan', 'Active Plan')}</p>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('billing.visibleToCustomers', 'Visible to new customers')}</p>
              </div>
              <button onClick={() => setForm(f => ({ ...f, active: !f.active }))}>
                {form.active ? <ToggleRight size={28} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={28} style={{ color: 'hsl(var(--muted-foreground))' }} />}
              </button>
            </div>
          </div>

          {form.name && form.priceMonthly && (
            <div className="card p-5">
              <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.planPreview', 'Plan Preview')}</h3>
              <div className="p-4 rounded-xl border-2" style={{ borderColor: 'hsl(var(--primary))', backgroundColor: 'hsl(var(--primary-light))' }}>
                <p className="font-bold text-base" style={{ color: 'hsl(var(--primary))' }}>{form.name}</p>
                {form.description && <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{form.description}</p>}
                <p className="text-2xl font-bold mt-2" style={{ color: 'hsl(var(--foreground))' }}>
                  ${form.priceMonthly}<span className="text-sm font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>/mo</span>
                </p>
                {form.priceAnnual && <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>${form.priceAnnual}/yr</p>}
                <div className="mt-3 space-y-1">
                  {form.limits.conversations_per_month && <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>✓ {parseInt(form.limits.conversations_per_month, 10).toLocaleString()} conversations/mo</p>}
                  {form.limits.max_branches && <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>✓ {form.limits.max_branches} branches</p>}
                  <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>✓ {form.features.length} features</p>
                  <p className="text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>✓ {form.trialDays}-day trial</p>
                </div>
              </div>
            </div>
          )}

          <div className="card p-5">
            <h3 className="font-semibold mb-2" style={{ color: 'hsl(var(--foreground))' }}>Stripe Sync</h3>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              On save, a Stripe Product and Price will be created or updated automatically if <code className="text-xs">STRIPE_SECRET_KEY</code> is configured. If Stripe is not set up, the plan is saved to the database only.
            </p>
          </div>
        </div>
      </div>
    </>
  );
}
