'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { Check, Loader2, Plus, Pencil, Trash2, AlertCircle, BadgeCheck, WifiOff, X, RefreshCw, Eye, EyeOff, Save, CreditCard, Globe, ToggleLeft, ToggleRight, KeyRound, CheckCircle2, Download, ChevronDown } from 'lucide-react';
import { getAdminBilling, getAdminBillingPlansAll, deleteAdminBillingPlan, syncAdminBillingPlan, getAdminGatewaySettings, saveAdminGatewaySettings } from '@client/api/admin';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { toast } from 'sonner';
import { STRIPE_SUBSCRIPTION_CURRENCIES } from '@/shared/billingCurrencies';

interface PlanFull {
  id: string; name: string; description: string;
  priceMonthly: number; priceAnnual: number; trialDays: number;
  features: string[]; limits: Record<string, unknown>;
  isActive: boolean; stripeStatus: string; razorpayStatus?: string;
  subscribers: number; mrr: number;
}

interface UsageData {
  totalConversations: number; activeBranches: number; apiCallsThisMonth: number;
}

interface InvoiceData {
  id: string; restaurant: string; plan: string;
  amount: number; status: string; date: string;
}

interface BillingData {
  plans: { id: string; name: string; price: number; features: string[]; subscribers: number; mrr: number; }[];
  usage: UsageData;
  invoices: InvoiceData[];
}

interface GatewaySettings {
  stripe_active: boolean;
  stripe_mode: 'test' | 'live';
  stripe_currency: string;
  stripe_promo_codes_enabled: boolean;
  payment_grace_period_days: number;
  stripe_live_secret_key_hint?: string;
  stripe_live_publishable_key_hint?: string;
  stripe_test_secret_key_hint?: string;
  stripe_test_publishable_key_hint?: string;
  razorpay_active: boolean;
  razorpay_mode: 'test' | 'live';
  razorpay_currency: string;
  razorpay_live_key_id_hint?: string;
  razorpay_live_key_secret_hint?: string;
  razorpay_test_key_id_hint?: string;
  razorpay_test_key_secret_hint?: string;
}

const planColors: Record<string, string> = {
  Starter: 'hsl(210, 100%, 40%)',
  Growth: 'hsl(142, 72%, 29%)',
  Pro: 'hsl(22, 89%, 48%)',
  Enterprise: 'hsl(231, 40%, 14%)',
};

function GatewayStatusBadge({ gateway, status }: { gateway: 'stripe' | 'razorpay'; status: string }) {
  const label = gateway === 'stripe' ? 'Stripe' : 'Razorpay';
  if (status === 'synced') {
    return (
      <span className="flex items-center gap-1 badge badge-success text-xs">
        <BadgeCheck size={11} /> {label} Synced
      </span>
    );
  }
  if (status === 'not_configured') {
    return (
      <span className="flex items-center gap-1 badge badge-neutral text-xs">
        <WifiOff size={11} /> {label} not configured
      </span>
    );
  }
  return (
    <span className="flex items-center gap-1 badge badge-warning text-xs">
      <AlertCircle size={11} /> {label} not synced
    </span>
  );
}

function StripeStatusBadge({ status }: { status: string }) {
  return <GatewayStatusBadge gateway="stripe" status={status} />;
}

function DeleteConfirmModal({ plan, onConfirm, onCancel, deleting }: {
  plan: PlanFull;
  onConfirm: () => void;
  onCancel: () => void;
  deleting: boolean;
}) {
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onCancel}>
      <div
        className="card p-6 max-w-md w-full mx-4 space-y-4"
        onClick={e => e.stopPropagation()}
        style={{ backgroundColor: 'hsl(var(--surface))' }}
      >
        <div className="flex items-center justify-between">
          <h3 className="font-bold text-base" style={{ color: 'hsl(var(--foreground))' }}>Delete Plan</h3>
          <button onClick={onCancel} style={{ color: 'hsl(var(--muted-foreground))' }}><X size={16} /></button>
        </div>
        <p className="text-sm" style={{ color: 'hsl(var(--foreground-secondary))' }}>
          Are you sure you want to delete <strong>{plan.name}</strong>?
          {plan.subscribers > 0 && (
            <span className="block mt-2 font-semibold" style={{ color: 'hsl(var(--warning))' }}>
              This plan has {plan.subscribers} active subscriber{plan.subscribers !== 1 ? 's' : ''}. The plan will be deactivated and archived on Stripe but existing subscriptions remain unaffected.
            </span>
          )}
        </p>
        <div className="flex justify-end gap-2">
          <button className="btn-secondary" onClick={onCancel} disabled={deleting}>Cancel</button>
          <button
            className="btn-danger"
            onClick={onConfirm}
            disabled={deleting}
            style={{ backgroundColor: 'hsl(var(--danger))', color: 'white', padding: '0.5rem 1rem', borderRadius: '0.5rem', fontWeight: 600, fontSize: '0.875rem', display: 'flex', alignItems: 'center', gap: '0.375rem' }}
          >
            {deleting ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={14} />}
            Delete Plan
          </button>
        </div>
      </div>
    </div>
  );
}

function KeyInput({ label, placeholder, hint, value, onChange, show, onToggleShow }: {
  label: string; placeholder: string; hint?: string;
  value: string; onChange: (v: string) => void;
  show: boolean; onToggleShow: () => void;
}) {
  return (
    <div>
      <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
        {hint ? `Replace ${label}` : label}
      </label>
      {hint && (
        <div className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs mb-1.5" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          <KeyRound size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />
          <span style={{ color: 'hsl(var(--muted-foreground))' }}>Current: <span className="font-mono font-semibold">{hint}</span></span>
          <span className="ml-auto badge badge-success text-xs">Saved</span>
        </div>
      )}
      <div className="relative">
        <input
          className="input-base pr-10 font-mono text-sm"
          type={show ? 'text' : 'password'}
          placeholder={placeholder}
          value={value}
          onChange={e => onChange(e.target.value)}
          autoComplete="off"
        />
        <button type="button" onClick={onToggleShow} className="absolute right-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }}>
          {show ? <EyeOff size={15} /> : <Eye size={15} />}
        </button>
      </div>
    </div>
  );
}

function ModePill({ mode, onChange }: { mode: 'test' | 'live'; onChange: (m: 'test' | 'live') => void }) {
  return (
    <div className="flex items-center gap-1 p-0.5 rounded-lg" style={{ backgroundColor: 'hsl(var(--muted))' }}>
      <button
        type="button"
        onClick={() => onChange('test')}
        className="px-3 py-1 rounded-md text-xs font-semibold transition-all"
        style={{
          backgroundColor: mode === 'test' ? 'hsl(45, 93%, 47%)' : 'transparent',
          color: mode === 'test' ? '#fff' : 'hsl(var(--muted-foreground))',
        }}
      >
        Test
      </button>
      <button
        type="button"
        onClick={() => onChange('live')}
        className="px-3 py-1 rounded-md text-xs font-semibold transition-all"
        style={{
          backgroundColor: mode === 'live' ? 'hsl(142, 72%, 29%)' : 'transparent',
          color: mode === 'live' ? '#fff' : 'hsl(var(--muted-foreground))',
        }}
      >
        Live
      </button>
    </div>
  );
}

function GatewaySettingsPanel() {
  const [settings, setSettings] = useState<GatewaySettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);

  const [stripeLiveSecret, setStripeLiveSecret] = useState('');
  const [stripeLivePub, setStripeLivePub] = useState('');
  const [stripeTestSecret, setStripeTestSecret] = useState('');
  const [stripeTestPub, setStripeTestPub] = useState('');
  const [showStripeLiveSecret, setShowStripeLiveSecret] = useState(false);
  const [showStripeTestSecret, setShowStripeTestSecret] = useState(false);

  const [razorpayLiveId, setRazorpayLiveId] = useState('');
  const [razorpayLiveSecret, setRazorpayLiveSecret] = useState('');
  const [razorpayTestId, setRazorpayTestId] = useState('');
  const [razorpayTestSecret, setRazorpayTestSecret] = useState('');
  const [showRazorpayLiveId, setShowRazorpayLiveId] = useState(false);
  const [showRazorpayLiveSecret, setShowRazorpayLiveSecret] = useState(false);
  const [showRazorpayTestId, setShowRazorpayTestId] = useState(false);
  const [showRazorpayTestSecret, setShowRazorpayTestSecret] = useState(false);

  // Collapsible key sections (default: open)
  const [stripeTestOpen, setStripeTestOpen] = useState(true);
  const [stripeLiveOpen, setStripeLiveOpen] = useState(true);
  const [razorpayTestOpen, setRazorpayTestOpen] = useState(true);
  const [razorpayLiveOpen, setRazorpayLiveOpen] = useState(true);

  useEffect(() => {
    getAdminGatewaySettings()
      .then((res: { settings: GatewaySettings }) => setSettings(res.settings))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const handleSave = useCallback(async () => {
    if (!settings) return;
    setSaving(true);
    setSaved(false);
    try {
      const mask = (k: string) => k.slice(0, 4) + '...' + k.slice(-4);
      const payload: Record<string, unknown> = {
        stripe_active: settings.stripe_active,
        stripe_mode: settings.stripe_mode,
        stripe_currency: settings.stripe_currency,
        stripe_promo_codes_enabled: settings.stripe_promo_codes_enabled,
        payment_grace_period_days: settings.payment_grace_period_days,
        razorpay_active: settings.razorpay_active,
        razorpay_mode: settings.razorpay_mode,
        razorpay_currency: settings.razorpay_currency,
      };
      // Capture trimmed values before async call
      const sls = stripeLiveSecret.trim();
      const slp = stripeLivePub.trim();
      const sts = stripeTestSecret.trim();
      const stp = stripeTestPub.trim();
      const rli = razorpayLiveId.trim();
      const rls = razorpayLiveSecret.trim();
      const rti = razorpayTestId.trim();
      const rts = razorpayTestSecret.trim();

      if (sls) payload.stripe_live_secret_key = sls;
      if (slp) payload.stripe_live_publishable_key = slp;
      if (sts) payload.stripe_test_secret_key = sts;
      if (stp) payload.stripe_test_publishable_key = stp;
      if (rli) payload.razorpay_live_key_id = rli;
      if (rls) payload.razorpay_live_key_secret = rls;
      if (rti) payload.razorpay_test_key_id = rti;
      if (rts) payload.razorpay_test_key_secret = rts;

      // Save first — only update UI hints and clear inputs on success
      await saveAdminGatewaySettings(payload);

      setSettings(s => {
        if (!s) return s;
        const next = { ...s };
        if (sls) next.stripe_live_secret_key_hint = mask(sls);
        if (slp) next.stripe_live_publishable_key_hint = slp.slice(0, 7) + '...';
        if (sts) next.stripe_test_secret_key_hint = mask(sts);
        if (stp) next.stripe_test_publishable_key_hint = stp.slice(0, 7) + '...';
        if (rli) next.razorpay_live_key_id_hint = mask(rli);
        if (rls) next.razorpay_live_key_secret_hint = mask(rls);
        if (rti) next.razorpay_test_key_id_hint = mask(rti);
        if (rts) next.razorpay_test_key_secret_hint = mask(rts);
        return next;
      });
      if (sls) setStripeLiveSecret('');
      if (slp) setStripeLivePub('');
      if (sts) setStripeTestSecret('');
      if (stp) setStripeTestPub('');
      if (rli) setRazorpayLiveId('');
      if (rls) setRazorpayLiveSecret('');
      if (rti) setRazorpayTestId('');
      if (rts) setRazorpayTestSecret('');

      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
      toast.success('Gateway settings saved');
    } catch {
      toast.error('Failed to save gateway settings');
    }
    setSaving(false);
  }, [settings, stripeLiveSecret, stripeLivePub, stripeTestSecret, stripeTestPub,
    razorpayLiveId, razorpayLiveSecret, razorpayTestId, razorpayTestSecret]);

  if (loading) {
    return <div className="flex justify-center py-12"><Loader2 className="animate-spin" size={24} /></div>;
  }
  if (!settings) {
    return <div className="card p-6 text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>Failed to load gateway settings</div>;
  }

  const stripeMode = settings.stripe_mode;
  const razorpayMode = settings.razorpay_mode;

  return (
    <div className="space-y-5 max-w-2xl">

      {/* ── Stripe ─────────────────────────────────────────────────────────── */}
      <div className="card p-6 space-y-5">
        <div className="flex items-center gap-2 mb-1">
          <CreditCard size={18} style={{ color: 'hsl(var(--primary))' }} />
          <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>Stripe</h3>
          <span className={`ml-2 badge text-xs ${stripeMode === 'live' ? 'badge-success' : 'badge-warning'}`}>
            {stripeMode === 'live' ? 'Live' : 'Test / Sandbox'}
          </span>
          <span className="ml-auto badge badge-neutral text-xs">Built-in</span>
        </div>

        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>Enable Stripe payments</p>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Used for credit/debit card checkout</p>
          </div>
          <button onClick={() => setSettings(s => s ? { ...s, stripe_active: !s.stripe_active } : s)}>
            {settings.stripe_active
              ? <ToggleRight size={28} style={{ color: 'hsl(var(--success))' }} />
              : <ToggleLeft size={28} style={{ color: 'hsl(var(--muted-foreground))' }} />}
          </button>
        </div>

        <div>
          <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>Active Mode</p>
          <ModePill mode={stripeMode} onChange={m => setSettings(s => s ? { ...s, stripe_mode: m } : s)} />
          <p className="text-xs mt-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {stripeMode === 'live' ? 'Using live keys — real charges apply.' : 'Using test keys — no real charges.'}
          </p>
        </div>

        <div className="space-y-3">
          <div className="rounded-xl overflow-hidden" style={{ border: '1px solid hsl(45,93%,47%,0.35)' }}>
            <button
              type="button"
              className="w-full flex items-center justify-between px-4 py-2.5"
              style={{ backgroundColor: 'hsl(45,93%,47%,0.08)' }}
              onClick={() => setStripeTestOpen(v => !v)}
            >
              <span className="text-xs font-bold uppercase tracking-wide" style={{ color: 'hsl(45, 80%, 35%)' }}>Test Keys (sk_test_ / pk_test_)</span>
              <ChevronDown size={14} style={{ color: 'hsl(45, 80%, 35%)', transform: stripeTestOpen ? 'rotate(180deg)' : undefined, transition: 'transform 0.2s' }} />
            </button>
            {stripeTestOpen && (
              <div className="px-4 pb-4 pt-3 space-y-3" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <KeyInput label="Test Secret Key" placeholder="sk_test_..." hint={settings.stripe_test_secret_key_hint}
                  value={stripeTestSecret} onChange={setStripeTestSecret} show={showStripeTestSecret} onToggleShow={() => setShowStripeTestSecret(v => !v)} />
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                    {settings.stripe_test_publishable_key_hint ? 'Replace Test Publishable Key' : 'Test Publishable Key'}
                  </label>
                  {settings.stripe_test_publishable_key_hint && (
                    <div className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs mb-1.5" style={{ backgroundColor: 'hsl(var(--surface))' }}>
                      <KeyRound size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />
                      <span style={{ color: 'hsl(var(--muted-foreground))' }}>Current: <span className="font-mono font-semibold">{settings.stripe_test_publishable_key_hint}</span></span>
                      <span className="ml-auto badge badge-success text-xs">Saved</span>
                    </div>
                  )}
                  <input className="input-base font-mono text-sm" type="text" placeholder="pk_test_..."
                    value={stripeTestPub} onChange={e => setStripeTestPub(e.target.value)} autoComplete="off" />
                </div>
              </div>
            )}
          </div>

          <div className="rounded-xl overflow-hidden" style={{ border: '1px solid hsl(142,72%,29%,0.35)' }}>
            <button
              type="button"
              className="w-full flex items-center justify-between px-4 py-2.5"
              style={{ backgroundColor: 'hsl(142,72%,29%,0.08)' }}
              onClick={() => setStripeLiveOpen(v => !v)}
            >
              <span className="text-xs font-bold uppercase tracking-wide" style={{ color: 'hsl(142, 60%, 28%)' }}>Live Keys (sk_live_ / pk_live_)</span>
              <ChevronDown size={14} style={{ color: 'hsl(142, 60%, 28%)', transform: stripeLiveOpen ? 'rotate(180deg)' : undefined, transition: 'transform 0.2s' }} />
            </button>
            {stripeLiveOpen && (
              <div className="px-4 pb-4 pt-3 space-y-3" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <KeyInput label="Live Secret Key" placeholder="sk_live_..." hint={settings.stripe_live_secret_key_hint}
                  value={stripeLiveSecret} onChange={setStripeLiveSecret} show={showStripeLiveSecret} onToggleShow={() => setShowStripeLiveSecret(v => !v)} />
                <div>
                  <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                    {settings.stripe_live_publishable_key_hint ? 'Replace Live Publishable Key' : 'Live Publishable Key'}
                  </label>
                  {settings.stripe_live_publishable_key_hint && (
                    <div className="flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs mb-1.5" style={{ backgroundColor: 'hsl(var(--surface))' }}>
                      <KeyRound size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />
                      <span style={{ color: 'hsl(var(--muted-foreground))' }}>Current: <span className="font-mono font-semibold">{settings.stripe_live_publishable_key_hint}</span></span>
                      <span className="ml-auto badge badge-success text-xs">Saved</span>
                    </div>
                  )}
                  <input className="input-base font-mono text-sm" type="text" placeholder="pk_live_..."
                    value={stripeLivePub} onChange={e => setStripeLivePub(e.target.value)} autoComplete="off" />
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Default Currency</label>
            <select className="input-base" value={settings.stripe_currency}
              onChange={e => setSettings(s => s ? { ...s, stripe_currency: e.target.value } : s)}>
              {STRIPE_SUBSCRIPTION_CURRENCIES.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Grace Period (days)</label>
            <input type="number" min="0" max="30" className="input-base"
              value={settings.payment_grace_period_days}
              onChange={e => setSettings(s => s ? { ...s, payment_grace_period_days: parseInt(e.target.value, 10) || 0 } : s)} />
          </div>
        </div>
      </div>

      {/* ── Razorpay ───────────────────────────────────────────────────────── */}
      <div className="card p-6 space-y-5">
        <div className="flex items-center gap-2 mb-1">
          <Globe size={18} style={{ color: 'hsl(228, 60%, 55%)' }} />
          <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>Razorpay</h3>
          <span className={`ml-2 badge text-xs ${razorpayMode === 'live' ? 'badge-success' : 'badge-warning'}`}>
            {razorpayMode === 'live' ? 'Live' : 'Test / Sandbox'}
          </span>
          <span className="ml-auto badge badge-neutral text-xs">For INR / India</span>
        </div>

        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>Enable Razorpay payments</p>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Show Razorpay checkout for INR / Indian customers</p>
          </div>
          <button onClick={() => setSettings(s => s ? { ...s, razorpay_active: !s.razorpay_active } : s)}>
            {settings.razorpay_active
              ? <ToggleRight size={28} style={{ color: 'hsl(var(--success))' }} />
              : <ToggleLeft size={28} style={{ color: 'hsl(var(--muted-foreground))' }} />}
          </button>
        </div>

        <div>
          <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>Active Mode</p>
          <ModePill mode={razorpayMode} onChange={m => setSettings(s => s ? { ...s, razorpay_mode: m } : s)} />
          <p className="text-xs mt-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {razorpayMode === 'live' ? 'Using live keys — real charges apply.' : 'Using test keys — no real charges.'}
          </p>
        </div>

        <div className="space-y-3">
          <div className="rounded-xl overflow-hidden" style={{ border: '1px solid hsl(45,93%,47%,0.35)' }}>
            <button
              type="button"
              className="w-full flex items-center justify-between px-4 py-2.5"
              style={{ backgroundColor: 'hsl(45,93%,47%,0.08)' }}
              onClick={() => setRazorpayTestOpen(v => !v)}
            >
              <span className="text-xs font-bold uppercase tracking-wide" style={{ color: 'hsl(45, 80%, 35%)' }}>Test Keys (rzp_test_)</span>
              <ChevronDown size={14} style={{ color: 'hsl(45, 80%, 35%)', transform: razorpayTestOpen ? 'rotate(180deg)' : undefined, transition: 'transform 0.2s' }} />
            </button>
            {razorpayTestOpen && (
              <div className="px-4 pb-4 pt-3 space-y-3" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <KeyInput label="Test Key ID" placeholder="rzp_test_..." hint={settings.razorpay_test_key_id_hint}
                  value={razorpayTestId} onChange={setRazorpayTestId} show={showRazorpayTestId} onToggleShow={() => setShowRazorpayTestId(v => !v)} />
                <KeyInput label="Test Key Secret" placeholder="Secret key" hint={settings.razorpay_test_key_secret_hint}
                  value={razorpayTestSecret} onChange={setRazorpayTestSecret} show={showRazorpayTestSecret} onToggleShow={() => setShowRazorpayTestSecret(v => !v)} />
              </div>
            )}
          </div>

          <div className="rounded-xl overflow-hidden" style={{ border: '1px solid hsl(142,72%,29%,0.35)' }}>
            <button
              type="button"
              className="w-full flex items-center justify-between px-4 py-2.5"
              style={{ backgroundColor: 'hsl(142,72%,29%,0.08)' }}
              onClick={() => setRazorpayLiveOpen(v => !v)}
            >
              <span className="text-xs font-bold uppercase tracking-wide" style={{ color: 'hsl(142, 60%, 28%)' }}>Live Keys (rzp_live_)</span>
              <ChevronDown size={14} style={{ color: 'hsl(142, 60%, 28%)', transform: razorpayLiveOpen ? 'rotate(180deg)' : undefined, transition: 'transform 0.2s' }} />
            </button>
            {razorpayLiveOpen && (
              <div className="px-4 pb-4 pt-3 space-y-3" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                <KeyInput label="Live Key ID" placeholder="rzp_live_..." hint={settings.razorpay_live_key_id_hint}
                  value={razorpayLiveId} onChange={setRazorpayLiveId} show={showRazorpayLiveId} onToggleShow={() => setShowRazorpayLiveId(v => !v)} />
                <KeyInput label="Live Key Secret" placeholder="Secret key" hint={settings.razorpay_live_key_secret_hint}
                  value={razorpayLiveSecret} onChange={setRazorpayLiveSecret} show={showRazorpayLiveSecret} onToggleShow={() => setShowRazorpayLiveSecret(v => !v)} />
              </div>
            )}
          </div>
        </div>

        <div>
          <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>Default Currency</label>
          <select className="input-base" value={settings.razorpay_currency}
            onChange={e => setSettings(s => s ? { ...s, razorpay_currency: e.target.value } : s)}>
            {['INR'].map(c => <option key={c} value={c}>{c}</option>)}
          </select>
        </div>
      </div>

      <div className="flex items-center gap-3">
        <button className="btn-primary" onClick={handleSave} disabled={saving}>
          {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
          Save Gateway Settings
        </button>
        {saved && (
          <span className="flex items-center gap-1.5 text-sm font-medium" style={{ color: 'hsl(var(--success, var(--primary)))' }}>
            <CheckCircle2 size={15} /> Saved
          </span>
        )}
      </div>
    </div>
  );
}

export default function BillingPage() {
  const { t, currentLang } = useLanguage();
  usePageHeader(t('admin.billing.pageTitle', "Subscription & Billing"), t('admin.billing.pageDesc', "Plans, usage, and billing overview"));

  const [billingData, setBillingData] = useState<BillingData | null>(null);
  const [plans, setPlans] = useState<PlanFull[]>([]);
  const [loading, setLoading] = useState(true);
  const [plansLoading, setPlansLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'plans' | 'usage' | 'invoices' | 'gateways'>('plans');
  const [deletingPlan, setDeletingPlan] = useState<PlanFull | null>(null);
  const [deleteInProgress, setDeleteInProgress] = useState(false);
  const [syncingPlanId, setSyncingPlanId] = useState<string | null>(null);

  const formatDate = (dateStr: string) => {
    const d = new Date(dateStr);
    return d.toLocaleDateString(currentLang, { month: 'short', day: 'numeric', year: 'numeric' });
  };

  useEffect(() => {
    getAdminBilling()
      .then(setBillingData)
      .catch(() => setBillingData(null))
      .finally(() => setLoading(false));
    getAdminBillingPlansAll()
      .then((res: { plans: PlanFull[] }) => setPlans(res.plans ?? []))
      .catch(() => setPlans([]))
      .finally(() => setPlansLoading(false));
  }, []);

  const handleDeleteConfirm = useCallback(async () => {
    if (!deletingPlan) return;
    setDeleteInProgress(true);
    try {
      await deleteAdminBillingPlan(deletingPlan.id);
      setPlans(prev => prev.map(p => p.id === deletingPlan.id ? { ...p, isActive: false } : p));
      toast.success(`Plan "${deletingPlan.name}" deactivated`);
    } catch {
      toast.error('Failed to delete plan');
    }
    setDeleteInProgress(false);
    setDeletingPlan(null);
  }, [deletingPlan]);

  const handleSyncPlan = useCallback(async (planId: string) => {
    setSyncingPlanId(planId);
    try {
      const res = await syncAdminBillingPlan(planId) as { stripeStatus: string; razorpayStatus?: string };
      setPlans(prev => prev.map(p => p.id === planId ? {
        ...p,
        stripeStatus: res.stripeStatus,
        razorpayStatus: res.razorpayStatus ?? p.razorpayStatus,
      } : p));
      const parts: string[] = [];
      if (res.stripeStatus === 'synced') parts.push('Stripe');
      if (res.razorpayStatus === 'synced') parts.push('Razorpay');
      toast.success(parts.length > 0 ? `Plan synced with ${parts.join(' & ')}` : 'Gateways not configured');
    } catch {
      toast.error('Failed to sync plan');
    }
    setSyncingPlanId(null);
  }, []);

  const usage = billingData?.usage;
  const invoices = billingData?.invoices ?? [];
  const totalMrr = plans.reduce((s, p) => s + p.mrr, 0);
  const totalSubs = plans.reduce((s, p) => s + p.subscribers, 0);

  return (
    <>
      {deletingPlan && (
        <DeleteConfirmModal
          plan={deletingPlan}
          onConfirm={handleDeleteConfirm}
          onCancel={() => setDeletingPlan(null)}
          deleting={deleteInProgress}
        />
      )}

      <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-6" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
        <div className="w-2 h-2 rounded-full bg-orange-400 animate-pulse" />
        <span className="text-sm font-semibold">{t('admin.billing.adminPanel', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">— {t('admin.billing.totalMrrStats', 'Total MRR: ${{mrr}} across {{subs}} subscribers', { mrr: totalMrr.toLocaleString(), subs: totalSubs.toString() })}</span>
      </div>

      <div className="flex items-center justify-between mb-6">
        <div className="flex gap-1 p-1 rounded-xl w-fit" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          {[
            { key: 'plans', label: t('admin.billing.tabPlans', 'Plans & Subscribers') },
            { key: 'usage', label: t('admin.billing.tabUsage', 'Platform Usage') },
            { key: 'invoices', label: t('admin.billing.tabInvoices', 'Invoices') },
            { key: 'gateways', label: 'Payment Gateways' },
          ].map(tab => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key as typeof activeTab)}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === tab.key ? 'bg-white shadow-sm' : ''}`}
              style={{ color: activeTab === tab.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
            >
              {tab.label}
            </button>
          ))}
        </div>
        {activeTab === 'plans' && (
          <Link href="/admin/billing/plans/new" className="btn-primary">
            <Plus size={15} /> Add Plan
          </Link>
        )}
      </div>

      {activeTab === 'plans' && (
        <div>
          {plansLoading ? (
            <div className="flex items-center justify-center py-20">
              <Loader2 className="animate-spin" size={32} />
            </div>
          ) : plans.length > 0 ? (
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
              {plans.map(plan => {
                const color = planColors[plan.name] ?? 'hsl(220, 9%, 46%)';
                const limitsMap = plan.limits as Record<string, unknown>;
                return (
                  <div key={plan.id} className="card p-6 flex flex-col" style={{ opacity: plan.isActive ? 1 : 0.6 }}>
                    <div className="flex items-start justify-between mb-3">
                      <div>
                        <div className="flex items-center gap-2 mb-0.5">
                          <h3 className="font-bold text-base" style={{ color: 'hsl(var(--foreground))' }}>{plan.name}</h3>
                          {!plan.isActive && <span className="badge badge-neutral text-xs">Inactive</span>}
                          {(plan.trialDays ?? 0) > 0 && <span className="badge badge-neutral text-xs">{plan.trialDays}d trial</span>}
                        </div>
                        {plan.description && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{plan.description}</p>}
                      </div>
                      <div className="flex gap-1 shrink-0">
                        <button
                          onClick={() => handleSyncPlan(plan.id)}
                          className="btn-ghost p-1.5"
                          title="Sync with Stripe"
                          disabled={syncingPlanId === plan.id}
                          style={{ color: 'hsl(var(--muted-foreground))' }}
                        >
                          {syncingPlanId === plan.id
                            ? <Loader2 size={14} className="animate-spin" />
                            : <RefreshCw size={14} />}
                        </button>
                        <Link href={`/admin/billing/plans/${plan.id}`} className="btn-ghost p-1.5" title="Edit plan">
                          <Pencil size={14} />
                        </Link>
                        <button
                          onClick={() => setDeletingPlan(plan)}
                          className="btn-ghost p-1.5"
                          title="Delete plan"
                          style={{ color: 'hsl(var(--danger))' }}
                        >
                          <Trash2 size={14} />
                        </button>
                      </div>
                    </div>

                    <p className="text-2xl font-bold mb-3" style={{ color }}>
                      ${plan.priceMonthly.toLocaleString()}<span className="text-sm font-normal" style={{ color: 'hsl(var(--muted-foreground))' }}>/mo</span>
                      {plan.priceAnnual > 0 && <span className="text-sm font-normal ml-2" style={{ color: 'hsl(var(--muted-foreground))' }}>(${plan.priceAnnual}/yr)</span>}
                    </p>

                    <div className="p-3 rounded-lg mb-3 flex justify-between items-center" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                      <div>
                        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Subscribers</span>
                        <p className="font-bold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{plan.subscribers}</p>
                      </div>
                      <div className="text-right">
                        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>MRR</span>
                        <p className="font-bold text-sm" style={{ color }}>${plan.mrr.toLocaleString()}</p>
                      </div>
                    </div>

                    {Object.keys(limitsMap).length > 0 && (
                      <div className="space-y-1 mb-3 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {limitsMap.conversations_per_month !== undefined && <p>💬 {limitsMap.conversations_per_month === 0 ? 'Unlimited' : String(limitsMap.conversations_per_month)} conversations/mo</p>}
                        {limitsMap.api_calls_per_minute !== undefined && <p>⚡ {limitsMap.api_calls_per_minute === 0 ? 'Unlimited' : String(limitsMap.api_calls_per_minute)} API calls/min</p>}
                        {limitsMap.concurrent_voice_calls !== undefined && <p>📞 {limitsMap.concurrent_voice_calls === 0 ? 'Unlimited' : String(limitsMap.concurrent_voice_calls)} concurrent voice calls</p>}
                        {limitsMap.max_branches !== undefined && <p>🏪 {limitsMap.max_branches === 0 ? 'Unlimited' : String(limitsMap.max_branches)} branches</p>}
                      </div>
                    )}

                    <ul className="space-y-1.5 flex-1">
                      {(plan.features as string[]).slice(0, 5).map((f: string) => (
                        <li key={f} className="flex items-center gap-2 text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                          <Check size={12} style={{ color }} />
                          {f}
                        </li>
                      ))}
                      {(plan.features as string[]).length > 5 && (
                        <li className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>+{(plan.features as string[]).length - 5} more</li>
                      )}
                    </ul>

                    <div className="mt-3 pt-3 flex flex-wrap gap-2" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                      <StripeStatusBadge status={plan.stripeStatus} />
                      {plan.razorpayStatus && (
                        <GatewayStatusBadge gateway="razorpay" status={plan.razorpayStatus} />
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="text-center py-16">
              <p className="text-sm mb-4" style={{ color: 'hsl(var(--muted-foreground))' }}>No plans configured yet</p>
              <Link href="/admin/billing/plans/new" className="btn-primary"><Plus size={15} /> Create First Plan</Link>
            </div>
          )}
        </div>
      )}

      {activeTab === 'usage' && (
        <div className="card p-5">
          <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.billing.usageOverview', 'Platform Usage Overview')}</h3>
          {loading ? (
            <div className="flex justify-center py-8"><Loader2 className="animate-spin" size={24} /></div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {[
                { label: t('admin.billing.totalConversations', 'Total AI Conversations'), value: (usage?.totalConversations ?? 0).toLocaleString() },
                { label: t('admin.billing.activeBranches', 'Active Branches'), value: (usage?.activeBranches ?? 0).toLocaleString() },
                { label: t('admin.billing.apiCallsThisMonth', 'API Calls This Month'), value: (usage?.apiCallsThisMonth ?? 0).toLocaleString() },
              ].map(u => (
                <div key={u.label} className="p-4 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
                  <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{u.label}</p>
                  <p className="text-lg font-bold" style={{ color: 'hsl(var(--foreground))' }}>{u.value}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {activeTab === 'invoices' && (
        <div className="space-y-3">
          {loading ? null : invoices.length > 0 && (
            <div className="flex justify-end">
              <button
                onClick={() => {
                  invoices.forEach((inv, idx) => {
                    const url = (inv as { pdfUrl?: string; hostedUrl?: string }).pdfUrl
                      ?? (inv as { pdfUrl?: string; hostedUrl?: string }).hostedUrl;
                    if (!url) return;
                    setTimeout(() => window.open(url, '_blank', 'noopener'), idx * 250);
                  });
                }}
                disabled={!invoices.some(i => (i as { pdfUrl?: string; hostedUrl?: string }).pdfUrl || (i as { pdfUrl?: string; hostedUrl?: string }).hostedUrl)}
                className="btn-secondary flex items-center gap-2 text-xs disabled:opacity-50"
              >
                <Download size={13} /> {t('admin.billing.downloadAll', 'Download All')}
              </button>
            </div>
          )}
          <div className="card overflow-hidden">
            {loading ? (
              <div className="flex justify-center py-8"><Loader2 className="animate-spin" size={24} /></div>
            ) : invoices.length > 0 ? (
              <table className="w-full">
                <thead>
                  <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                    {[
                      { key: 'restaurant', label: t('admin.billing.headerRestaurant', 'Restaurant') },
                      { key: 'plan', label: t('admin.billing.headerPlan', 'Plan') },
                      { key: 'amount', label: t('admin.billing.headerAmount', 'Amount') },
                      { key: 'date', label: t('admin.billing.headerDate', 'Date') },
                      { key: 'status', label: t('admin.billing.headerStatus', 'Status') },
                      { key: 'gateway', label: 'Gateway' },
                      { key: 'download', label: '' },
                    ].map(h => (
                      <th key={h.key} className="text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h.label}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {invoices.map((inv, idx) => {
                    const ext = inv as { pdfUrl?: string; hostedUrl?: string; gateway?: string };
                    const downloadUrl = ext.pdfUrl ?? ext.hostedUrl;
                    return (
                    <tr key={inv.id} className="table-row-hover" style={{ borderBottom: idx < invoices.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                      <td className="px-5 py-3 text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{inv.restaurant}</td>
                      <td className="px-5 py-3"><span className="badge badge-neutral">{inv.plan}</span></td>
                      <td className="px-5 py-3 font-semibold tabular-nums text-sm" style={{ color: 'hsl(var(--foreground))' }}>${inv.amount.toLocaleString()}</td>
                      <td className="px-5 py-3 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{formatDate(inv.date)}</td>
                      <td className="px-5 py-3">
                        <span className={`badge ${inv.status === 'paid' ? 'badge-success' : inv.status === 'cancelled' ? 'badge-danger' : 'badge-warning'}`}>{t(`admin.billing.status.${inv.status}`, inv.status)}</span>
                      </td>
                      <td className="px-5 py-3">
                        <span className="badge badge-neutral text-xs capitalize">{ext.gateway ?? 'Stripe'}</span>
                      </td>
                      <td className="px-5 py-3 text-right">
                        {downloadUrl ? (
                          <a href={downloadUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs font-medium" style={{ color: 'hsl(var(--primary))' }}>
                            <Download size={12} /> {t('admin.billing.download', 'Download')}
                          </a>
                        ) : (
                          <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>—</span>
                        )}
                      </td>
                    </tr>
                  );})}
                </tbody>
              </table>
            ) : (
              <p className="text-sm py-10 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.billing.noInvoices', 'No invoices yet')}</p>
            )}
          </div>
        </div>
      )}

      {activeTab === 'gateways' && <GatewaySettingsPanel />}
    </>
  );
}
