'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { Check, Loader2, Plus, Pencil, Trash2, AlertCircle, BadgeCheck, WifiOff, X, RefreshCw } from 'lucide-react';
import { getAdminBilling, getAdminBillingPlansAll, deleteAdminBillingPlan, syncAdminBillingPlan } from '@client/api/admin';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { toast } from 'sonner';

interface PlanFull {
  id: string; name: string; description: string;
  priceMonthly: number; priceAnnual: number; trialDays: number;
  features: string[]; limits: Record<string, unknown>;
  isActive: boolean; stripeStatus: 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[];
}

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 StripeStatusBadge({ status }: { status: string }) {
  if (status === 'synced') {
    return (
      <span className="flex items-center gap-1 badge badge-success text-xs">
        <BadgeCheck size={11} /> Stripe Synced
      </span>
    );
  }
  if (status === 'not_configured') {
    return (
      <span className="flex items-center gap-1 badge badge-neutral text-xs">
        <WifiOff size={11} /> Stripe not configured
      </span>
    );
  }
  return (
    <span className="flex items-center gap-1 badge badge-warning text-xs">
      <AlertCircle size={11} /> Not synced
    </span>
  );
}

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>
  );
}

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'>('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 };
      setPlans(prev => prev.map(p => p.id === planId ? { ...p, stripeStatus: res.stripeStatus } : p));
      toast.success(res.stripeStatus === 'synced' ? 'Plan synced with Stripe' : 'Stripe not configured');
    } catch {
      toast.error('Failed to sync plan with Stripe');
    }
    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') },
          ].map(tab => (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key as 'plans' | 'usage' | 'invoices')}
              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>}
                        </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" style={{ borderTop: '1px solid hsl(var(--border))' }}>
                      <StripeStatusBadge status={plan.stripeStatus} />
                    </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="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') }
                  ].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) => (
                  <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>
                  </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>
      )}
    </>
  );
}
