// frontend/src/pages/BillingPage.jsx
import { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext.jsx';
import { useT } from '../i18n/translations.js';
import { api } from '../context/AuthContext.jsx';
import { Card, Button, Badge, StatusBadge } from '../components/ui/index.jsx';
import { CheckCircle2, ExternalLink } from 'lucide-react';
import toast from 'react-hot-toast';
import { format } from 'date-fns';

const PLANS = [
  {
    id: 'starter',
    price: 29,
    features: { en: ['3 video scripts/day', '3 X posts/day', 'Blog + Newsletter', 'All 10 agents', 'Shared AI (no API key needed)', '14-day trial'], ro: ['3 scripturi video/zi', '3 postări X/zi', 'Blog + Newsletter', 'Toți 10 agenții', 'AI partajat (fără API key)', 'Trial 14 zile'] }
  },
  {
    id: 'pro',
    price: 79,
    popular: true,
    features: { en: ['5 video scripts/day', '5 X posts/day', 'Blog + Newsletter', 'All 10 agents', 'Your own API key (BYOK)', 'Unlimited runs', '14-day trial'], ro: ['5 scripturi video/zi', '5 postări X/zi', 'Blog + Newsletter', 'Toți 10 agenții', 'Propriul API key (BYOK)', 'Rulări nelimitate', 'Trial 14 zile'] }
  },
  {
    id: 'agency',
    price: 199,
    features: { en: ['10 video scripts/day', '10 X posts/day', 'Blog + Newsletter', 'All 10 agents', 'Your own API key (BYOK)', 'White label', 'Up to 10 sub-clients', '14-day trial'], ro: ['10 scripturi video/zi', '10 postări X/zi', 'Blog + Newsletter', 'Toți 10 agenții', 'Propriul API key (BYOK)', 'White label', 'Până la 10 sub-clienți', 'Trial 14 zile'] }
  },
];

export default function BillingPage() {
  const { user, refreshUser } = useAuth();
  const t = useT(user?.locale);
  const locale = user?.locale || 'en';
  const [portalLoading, setPortalLoading] = useState(false);
  const [checkoutLoading, setCheckoutLoading] = useState(null);

  const openPortal = async () => {
    setPortalLoading(true);
    try {
      const { data } = await api.post('/stripe/portal');
      window.location.href = data.url;
    } catch { toast.error('Failed to open billing portal'); }
    setPortalLoading(false);
  };

  const checkout = async (planId) => {
    setCheckoutLoading(planId);
    try {
      const { data } = await api.post('/stripe/checkout', { planId });
      window.location.href = data.url;
    } catch { toast.error('Failed to start checkout'); }
    setCheckoutLoading(null);
  };

  const planNames = { starter: 'Starter', pro: 'Pro', agency: 'Agency' };

  return (
    <div className="space-y-8">
      <h1 className="text-2xl font-semibold text-gray-900">{t('billing.title')}</h1>

      {/* Current plan card */}
      <Card className="p-6">
        <div className="flex items-start justify-between">
          <div>
            <p className="text-sm text-gray-500 mb-1">{t('billing.currentPlan')}</p>
            <div className="flex items-center gap-2">
              <h2 className="text-xl font-semibold text-gray-900">{planNames[user?.planId] || 'Free'}</h2>
              <StatusBadge status={user?.status} />
            </div>
            {user?.status === 'trial' && user?.trialEndsAt && (
              <p className="text-sm text-amber-600 mt-1">
                {t('billing.trialEnds')}: {format(new Date(user.trialEndsAt), 'MMMM d, yyyy')}
              </p>
            )}
            {user?.currentPeriodEnd && user?.status === 'active' && (
              <p className="text-sm text-gray-400 mt-1">
                {t('billing.renewsOn')}: {format(new Date(user.currentPeriodEnd), 'MMMM d, yyyy')}
              </p>
            )}
          </div>
          {user?.stripeCustomerId && (
            <Button variant="secondary" onClick={openPortal} loading={portalLoading}>
              <ExternalLink size={14} />
              {t('billing.manage')}
            </Button>
          )}
        </div>
      </Card>

      {/* Plan cards */}
      <div>
        <h2 className="text-lg font-semibold text-gray-900 mb-4">{t('billing.upgrade')}</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {PLANS.map(plan => {
            const isCurrent = user?.planId === plan.id;
            return (
              <div
                key={plan.id}
                className={`relative rounded-2xl border-2 p-6 flex flex-col transition-all ${
                  plan.popular
                    ? 'border-brand-500 shadow-lg shadow-brand-100'
                    : isCurrent
                    ? 'border-gray-300'
                    : 'border-gray-200'
                }`}
              >
                {plan.popular && (
                  <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                    <span className="bg-brand-600 text-white text-xs font-semibold px-3 py-1 rounded-full">
                      {t('billing.mostPopular')}
                    </span>
                  </div>
                )}

                <div className="mb-4">
                  <h3 className="text-lg font-semibold text-gray-900">{planNames[plan.id]}</h3>
                  <div className="flex items-baseline gap-1 mt-1">
                    <span className="text-3xl font-bold text-gray-900">${plan.price}</span>
                    <span className="text-gray-400 text-sm">{t('billing.perMonth')}</span>
                  </div>
                </div>

                <ul className="space-y-2 flex-1 mb-6">
                  {(plan.features[locale] || plan.features.en).map((f, i) => (
                    <li key={i} className="flex items-start gap-2 text-sm text-gray-600">
                      <CheckCircle2 size={14} className="text-brand-500 mt-0.5 flex-shrink-0" />
                      {f}
                    </li>
                  ))}
                </ul>

                {isCurrent ? (
                  <div className="text-center py-2">
                    <Badge variant="success">Current plan</Badge>
                  </div>
                ) : (
                  <Button
                    onClick={() => checkout(plan.id)}
                    loading={checkoutLoading === plan.id}
                    variant={plan.popular ? 'primary' : 'secondary'}
                    className="w-full"
                  >
                    {user?.status === 'trial' ? 'Activate' : 'Switch'} to {planNames[plan.id]}
                  </Button>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
