'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/auth';
import { useAuth } from '@/lib/auth-context';
import PaymentModal from '@/components/ui/payment-modal';
import { useT } from '@/i18n';
import { Zap, CheckCircle } from 'lucide-react';

interface Quota {
  dailyLimit: number;
  used: number;
  dailyRemaining: number;
  extra: number;
  totalRemaining: number;
}

const PACKAGES = [
  { id: 'PACKAGE_10', planType: 'PACKAGE', amount: 4.9, quotaAmount: 10, labelKey: 'package10' as const, descKey: 'package10Desc' as const },
  { id: 'PACKAGE_50', planType: 'PACKAGE', amount: 9.9, quotaAmount: 50, labelKey: 'package50' as const, descKey: 'package50Desc' as const, popular: true },
  { id: 'PACKAGE_300', planType: 'PACKAGE', amount: 49, quotaAmount: 300, labelKey: 'package300' as const, descKey: 'package300Desc' as const },
];

export default function PackagesPage() {
  const t = useT();
  const { isLoggedIn } = useAuth();
  const [quota, setQuota] = useState<Quota | null>(null);
  const [loading, setLoading] = useState(true);
  const [payLoading, setPayLoading] = useState<string | null>(null);
  const [payChannel] = useState<'wxpay' | 'alipay'>('alipay');
  const [paymentModal, setPaymentModal] = useState<{
    open: boolean; orderNo: string; payResult: any; payChannel: 'wxpay' | 'alipay';
  }>({ open: false, orderNo: '', payResult: {}, payChannel: 'alipay' });
  const [success, setSuccess] = useState<string | null>(null);

  useEffect(() => {
    if (!isLoggedIn) { setLoading(false); return; }
    apiFetch('/sandbox/quota')
      .then(r => r.json())
      .then(data => setQuota(data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [isLoggedIn]);

  async function handleBuy(pkg: typeof PACKAGES[0]) {
    setPayLoading(pkg.id);
    setSuccess(null);
    try {
      const res = await apiFetch('/orders/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount: pkg.amount, planType: pkg.planType, payChannel }),
      });
      const data = await res.json();

      if (data.order && data.payResult) {
        const payUrl = data.payResult.payUrl || data.payResult.redirectUrl;
        const qrCode = data.payResult.qrcode || data.payResult.codeUrl;

        if (payUrl || qrCode) {
          setPaymentModal({ open: true, orderNo: data.order.orderNo, payResult: data.payResult, payChannel });
        }
      }
    } catch (e) {
      console.error(e);
    }
    setPayLoading(null);
  }

  function handlePaymentPaid() {
    setPaymentModal(prev => ({ ...prev, open: false }));
    setSuccess(t.packages.purchaseSuccess.replace('{n}', '50'));
    apiFetch('/sandbox/quota').then(r => r.ok && r.json()).then(d => d && setQuota(d));
  }

  if (!isLoggedIn) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-20 text-center">
        <Zap className="h-12 w-12 text-brand-600 mx-auto mb-4" />
        <h1 className="text-2xl font-bold text-foreground mb-2">{t.packages.title}</h1>
        <p className="text-muted-foreground mb-6">{t.packages.desc}</p>
        <Button asChild><Link href="/auth">{t.common.login}</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Link href="/practices" className="text-sm text-muted-foreground hover:text-foreground mb-4 inline-block">
        &larr; {t.practices.title}
      </Link>

      <div className="mb-8">
        <h1 className="text-3xl font-bold text-foreground">{t.packages.title}</h1>
        <p className="mt-2 text-muted-foreground">{t.packages.desc}</p>
      </div>

      {quota && (
        <div className="bg-card rounded-2xl border border-border p-6 mb-8">
          <h2 className="font-semibold text-foreground mb-3">{t.packages.currentQuota}</h2>
          <div className="flex flex-wrap gap-6">
            <div>
              <span className="text-sm text-muted-foreground">{t.packages.dailyQuota.replace('{used}', String(quota.used)).replace('{limit}', String(quota.dailyLimit))}</span>
            </div>
            <div>
              <span className="text-sm text-muted-foreground">{t.packages.extraQuota.replace('{n}', String(quota.extra))}</span>
            </div>
          </div>
        </div>
      )}

      {success && (
        <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-xl p-4 mb-6 flex items-center gap-3">
          <CheckCircle className="h-5 w-5 text-green-600 shrink-0" />
          <span className="text-sm text-green-800 dark:text-green-300">{success}</span>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {PACKAGES.map(pkg => (
          <div key={pkg.id} className={`bg-card rounded-2xl border-2 p-6 relative transition-all hover:shadow-md ${
            pkg.popular ? 'border-brand-600' : 'border-border'
          }`}>
            {pkg.popular && (
              <span className="absolute -top-3 left-1/2 -translate-x-1/2 bg-brand-600 text-white text-xs font-medium px-3 py-0.5 rounded-full">
                {t.packages.popular}
              </span>
            )}
            <div className="text-center mb-4">
              <div className="text-3xl font-bold text-foreground">{t.packages.price.replace('{price}', String(pkg.amount))}</div>
              <div className="text-sm text-muted-foreground mt-1">{t.packages.quota.replace('{n}', String(pkg.quotaAmount))}</div>
            </div>
            <div className="text-center mb-6">
              <div className="font-medium text-foreground">{t.packages[pkg.labelKey]}</div>
              <div className="text-xs text-muted-foreground mt-1">{t.packages[pkg.descKey]}</div>
            </div>
            <Button
              onClick={() => handleBuy(pkg)}
              disabled={payLoading === pkg.id}
              className={`w-full ${pkg.popular ? '' : 'variant-outline'}`}
              variant={pkg.popular ? 'default' : 'outline'}
            >
              {payLoading === pkg.id ? (
                <span className="flex items-center gap-2">
                  <span className="animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full" />
                  {t.packages.buying}
                </span>
              ) : t.packages.buy}
            </Button>
          </div>
        ))}
      </div>

      <div className="mt-8 text-center">
        <p className="text-sm text-muted-foreground">
          {t.packages.orUpgrade}{' '}
          <Link href="/my/member" className="text-brand-600 hover:underline">{t.member.title}</Link>
        </p>
      </div>

      <PaymentModal
        open={paymentModal.open}
        orderNo={paymentModal.orderNo}
        payResult={paymentModal.payResult}
        payChannel={paymentModal.payChannel}
        onClose={() => setPaymentModal(prev => ({ ...prev, open: false }))}
        onPaid={handlePaymentPaid}
      />
    </div>
  );
}
