'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { apiFetch } from '../../../lib/auth';
import { Skeleton } from '@/components/ui/skeleton';
import { useT } from '@/i18n';

interface Subscription {
  id: number; plan: string; startDate: string; endDate: string; status: string;
}

interface Order {
  id: number; orderNo: string; amount: number; planType: string; status: string; createdAt: string;
}

const PLANS = [
  { id: 'FREE', nameKey: 'planFree' as const, price: 0, period: '', popular: false, features: ['featureSandboxFree', 'featureModelsFree', 'featurePromptsFree', 'featureCoursesFree', 'featureAdsFree'] as const },
  { id: 'MONTHLY', nameKey: 'planMonthly' as const, price: 29.9, period: 'perMonth', popular: true, features: ['featureSandboxPro', 'featureModelsPro', 'featurePromptsPro', 'featureCoursesPro', 'featureAdsPro'] as const },
  { id: 'YEARLY', nameKey: 'planYearly' as const, price: 199, period: 'perYear', popular: false, features: ['featureSandboxUnlimited', 'featureModelsPremium', 'featurePromptsPremium', 'featureCoursesPremium', 'featureAdsPremium'] as const },
];

const FEATURE_LABELS = ['featureSandbox', 'featureModels', 'featurePrompts', 'featureCourses', 'featureAds'] as const;

export default function MemberPage() {
  const t = useT();
  const [subscription, setSubscription] = useState<Subscription | null>(null);
  const [orders, setOrders] = useState<Order[]>([]);
  const [quota, setQuota] = useState<{ used: number; remaining: number; dailyLimit: number } | null>(null);
  const [loading, setLoading] = useState(true);
  const [payLoading, setPayLoading] = useState<string | null>(null);

  useEffect(() => { loadData(); }, []);

  async function loadData() {
    try {
      const [subRes, ordersRes, quotaRes] = await Promise.all([
        apiFetch('/subscriptions/current').catch(() => ({ ok: false })),
        apiFetch('/orders'),
        apiFetch('/sandbox/quota'),
      ]);
      if (subRes.ok) setSubscription(await subRes.json());
      const ordersData = await ordersRes.json();
      setOrders(ordersData.items || []);
      const quotaData = await quotaRes.json();
      if (quotaData.remaining !== undefined) setQuota(quotaData);
    } catch (e) { console.error(e) }
    setLoading(false);
  }

  async function handleSubscribe(planType: string) {
    setPayLoading(planType);
    try {
      const res = await apiFetch('/orders/create', {
        method: 'POST',
        body: JSON.stringify({
          amount: planType === 'MONTHLY' ? 29.9 : 199,
          planType, payChannel: 'wxpay',
        }),
      });
      const data = await res.json();
      if (data.order && data.payResult) {
        alert('订单创建成功，请扫码支付（模拟模式）');
        loadData();
      }
    } catch (e) { console.error(e) }
    setPayLoading(null);
  }

  if (loading) return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Skeleton className="h-8 w-48 mb-2" />
      <Skeleton className="h-5 w-64 mb-8" />
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        {[1,2,3].map(i => <Skeleton key={i} className="h-72 rounded-2xl" />)}
      </div>
    </div>
  );

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="mb-8">
        <Link href="/my" className="text-sm text-muted-foreground hover:text-brand-600 mb-2 inline-block">&larr; 返回我的</Link>
        <h1 className="text-3xl font-bold text-foreground">{t.member.title}</h1>
        <p className="mt-2 text-muted-foreground">{t.member.desc}</p>
      </div>

      {quota && (
        <div className="bg-card rounded-2xl border border-border p-6 mb-8">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-foreground">{t.member.dailyQuota}</span>
            <span className="text-sm text-muted-foreground">{t.member.used.replace('{n}', String(quota.used))} / {quota.dailyLimit}</span>
          </div>
          <div className="w-full bg-muted rounded-full h-3">
            <div className="bg-brand-600 h-3 rounded-full transition-all" style={{ width: `${Math.min((quota.used / quota.dailyLimit) * 100, 100)}%` }} />
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        {PLANS.map(plan => {
          const isCurrent = subscription?.plan === plan.id;
          return (
            <div key={plan.id} className={`bg-card rounded-2xl border-2 p-6 flex flex-col ${isCurrent ? 'border-brand-600' : plan.popular ? 'border-brand-400' : 'border-border'}`}>
              {plan.popular && !isCurrent && (
                <span className="self-start text-xs font-medium px-2 py-0.5 bg-brand-600 text-white rounded-full mb-3">{t.member.popular}</span>
              )}
              {isCurrent && (
                <span className="self-start text-xs font-medium px-2 py-0.5 bg-green-600 text-white rounded-full mb-3">{t.member.currentPlan_badge}</span>
              )}
              <h3 className="text-lg font-semibold text-foreground mb-1">{t.member[plan.nameKey]}</h3>
              <div className="mb-4">
                {plan.price > 0 ? (
                  <span className="text-3xl font-bold text-foreground">{plan.price === 29.9 ? t.member.priceMonthly : t.member.priceYearly}<span className="text-sm font-normal text-muted-foreground">{t.member[plan.period]}</span></span>
                ) : (
                  <span className="text-2xl font-bold text-foreground">¥0</span>
                )}
              </div>
              <div className="space-y-2 flex-1 mb-6">
                {(plan.id === 'FREE' ? FEATURE_LABELS : FEATURE_LABELS).map((f, fi) => (
                  <div key={f} className="flex items-center gap-2 text-sm">
                    <span className="text-green-600 text-xs">✓</span>
                    <span className="text-muted-foreground">{t.member[f]}</span>
                    <span className="ml-auto text-xs text-foreground font-medium">{t.member[plan.features[fi]]}</span>
                  </div>
                ))}
              </div>
              {plan.id !== 'FREE' && (
                <button onClick={() => handleSubscribe(plan.id)} disabled={payLoading === plan.id || isCurrent}
                  className={`w-full py-2.5 rounded-xl text-sm font-medium transition-all ${isCurrent ? 'bg-muted text-muted-foreground cursor-default' : plan.popular ? 'bg-brand-600 text-white hover:bg-brand-700' : 'border border-border text-foreground hover:bg-accent'} disabled:opacity-50`}>
                  {payLoading === plan.id ? t.member.processing : isCurrent ? t.member.currentPlan_badge : t.member.subscribe}
                </button>
              )}
            </div>
          );
        })}
      </div>

      <div className="bg-card rounded-2xl border border-border p-6">
        <h2 className="text-lg font-semibold text-foreground mb-4">{t.member.orderHistory}</h2>
        {orders.length === 0 ? (
          <p className="text-muted-foreground text-center py-8">{t.member.noOrders}</p>
        ) : (
          <div className="space-y-3">
            {orders.map(order => (
              <div key={order.id} className="flex items-center justify-between p-4 rounded-xl border border-border">
                <div>
                  <div className="font-medium text-foreground">{t.member[order.planType === 'YEARLY' ? 'yearly' : 'monthly']}</div>
                  <div className="text-sm text-muted-foreground">{new Date(order.createdAt).toLocaleDateString()}</div>
                </div>
                <div className="text-right">
                  <div className="font-semibold text-foreground">¥{order.amount}</div>
                  <span className={`text-xs px-2 py-0.5 rounded ${order.status === 'PAID' ? 'bg-green-100 text-green-700' : order.status === 'PENDING' ? 'bg-yellow-100 text-yellow-700' : 'bg-muted text-muted-foreground'}`}>
                    {order.status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
