import { useMemo, useState } from "react";
import {
  AlertCircle,
  Calendar,
  Check,
  ChevronLeft,
  ChevronRight,
  CircleDollarSign,
  Film,
  Filter,
  Image as ImageIcon,
  Layers,
  Loader2,
  MessageSquareText,
  PackagePlus,
  Search,
  Sparkles,
  TrendingDown,
  WalletCards,
  X,
} from "lucide-react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { useBalance, usePurchase, useRecords } from "../../hooks/useUsage";
import type { BillingRecord } from "../../lib/api/usage";

const PAGE_SIZE = 30;

const OP_META: Record<string, { label: string; category: string; icon: typeof Film; color: string }> = {
  outline_generate: { label: "大纲生成", category: "剧本", icon: MessageSquareText, color: "#2563eb" },
  episode_generate: { label: "分集生成", category: "剧本", icon: MessageSquareText, color: "#3b82f6" },
  character_extract: { label: "角色提取", category: "剧本", icon: Layers, color: "#0f766e" },
  scene_extract: { label: "场景提取", category: "剧本", icon: Layers, color: "#14b8a6" },
  storyboard_generate: { label: "分镜生成", category: "分镜", icon: Layers, color: "#7c3aed" },
  storyboard_prompt_generate: { label: "提示词生成", category: "分镜", icon: MessageSquareText, color: "#8b5cf6" },
  image_generate: { label: "图片生成", category: "图片", icon: ImageIcon, color: "#ea580c" },
  character_image_generate: { label: "角色图生成", category: "图片", icon: ImageIcon, color: "#f97316" },
  scene_image_generate: { label: "场景图生成", category: "图片", icon: ImageIcon, color: "#fb923c" },
  video_generate: { label: "视频生成", category: "视频", icon: Film, color: "#dc2626" },
  assembly: { label: "视频合成", category: "合成", icon: Film, color: "#475569" },
  recharge: { label: "积分充值", category: "充值", icon: PackagePlus, color: "#16a34a" },
};

const PACKAGES = [
  { id: "starter", label: "入门包", credits: 1_000, price: "¥9.9", desc: "适合个人试用" },
  { id: "basic", label: "基础包", credits: 5_000, price: "¥39", desc: "适合小团队" },
  { id: "pro", label: "专业包", credits: 20_000, price: "¥129", desc: "高频创作推荐" },
  { id: "enterprise", label: "企业包", credits: 100_000, price: "¥499", desc: "适合批量生产" },
];

type QuickFilter = "all" | "consume" | "recharge" | "failed";

const money = (value: number | string | null | undefined) => Number(value ?? 0).toLocaleString();

const isRecharge = (record: BillingRecord) =>
  record.operation === "recharge" || record.modality === "RECHARGE";

const isSuccess = (record: BillingRecord) => record.success !== false;

const getMeta = (operation: string) =>
  OP_META[operation] ?? { label: operation || "未知操作", category: "其他", icon: CircleDollarSign, color: "#64748b" };

const formatDateTime = (value?: string) => {
  if (!value) return "-";
  return value.replace("T", " ").slice(0, 16);
};

const dayKey = (value?: string) => {
  if (!value) return "未知";
  const date = value.slice(5, 10);
  return date || "未知";
};

function StatCard({
  label,
  value,
  caption,
  icon: Icon,
  tone,
}: {
  label: string;
  value: string;
  caption: string;
  icon: typeof Sparkles;
  tone: string;
}) {
  return (
    <div className="rounded-xl border border-border bg-card p-5">
      <div className="flex items-center justify-between gap-3">
        <div>
          <div className="text-xs text-muted-foreground">{label}</div>
          <div className="mt-2 text-2xl font-semibold text-foreground">{value}</div>
          <div className="mt-1 text-xs text-muted-foreground">{caption}</div>
        </div>
        <div className={`flex h-11 w-11 items-center justify-center rounded-lg ${tone}`}>
          <Icon className="h-5 w-5" />
        </div>
      </div>
    </div>
  );
}

function EmptyState() {
  return (
    <div className="flex flex-col items-center justify-center py-14 text-center">
      <div className="mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-muted">
        <Search className="h-5 w-5 text-muted-foreground" />
      </div>
      <div className="text-sm font-medium text-foreground">暂无匹配的积分记录</div>
      <div className="mt-1 text-xs text-muted-foreground">调整筛选条件，或翻到其他分页查看历史记录。</div>
    </div>
  );
}

export function UsageManagement() {
  const [dateRange, setDateRange] = useState({ start: "", end: "" });
  const [selectedType, setSelectedType] = useState("");
  const [quickFilter, setQuickFilter] = useState<QuickFilter>("all");
  const [page, setPage] = useState(0);
  const [showPurchaseModal, setShowPurchaseModal] = useState(false);
  const [selectedPackage, setSelectedPackage] = useState("pro");
  const [purchased, setPurchased] = useState(false);

  const { data: balance } = useBalance();
  const { data: recordsPage, isLoading } = useRecords(PAGE_SIZE, page * PAGE_SIZE);
  const purchase = usePurchase();

  const records: BillingRecord[] = recordsPage?.items ?? [];
  const totalRecords = recordsPage?.total ?? 0;
  const pageCount = Math.max(1, Math.ceil(totalRecords / PAGE_SIZE));

  const filteredRecords = useMemo(() => {
    return records.filter((record) => {
      if (selectedType && record.operation !== selectedType) return false;
      if (dateRange.start && record.createdAt < `${dateRange.start}T00:00:00`) return false;
      if (dateRange.end && record.createdAt > `${dateRange.end}T23:59:59`) return false;
      if (quickFilter === "consume" && isRecharge(record)) return false;
      if (quickFilter === "recharge" && !isRecharge(record)) return false;
      if (quickFilter === "failed" && isSuccess(record)) return false;
      return true;
    });
  }, [dateRange.end, dateRange.start, quickFilter, records, selectedType]);

  const pageStats = useMemo(() => {
    const consumed = filteredRecords
      .filter((record) => !isRecharge(record))
      .reduce((sum, record) => sum + Number(record.credits ?? 0), 0);
    const recharged = filteredRecords
      .filter(isRecharge)
      .reduce((sum, record) => sum + Number(record.credits ?? 0), 0);
    const failed = filteredRecords.filter((record) => !isSuccess(record)).length;
    const categoryTotals = new Map<string, number>();

    filteredRecords.filter((record) => !isRecharge(record)).forEach((record) => {
      const meta = getMeta(record.operation);
      categoryTotals.set(meta.category, (categoryTotals.get(meta.category) ?? 0) + Number(record.credits ?? 0));
    });

    const topCategory = [...categoryTotals.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? "暂无";
    return { consumed, recharged, failed, topCategory };
  }, [filteredRecords]);

  const dailyData = useMemo(() => {
    const grouped = new Map<string, { day: string; consumed: number; recharged: number }>();
    filteredRecords.forEach((record) => {
      const key = dayKey(record.createdAt);
      const item = grouped.get(key) ?? { day: key, consumed: 0, recharged: 0 };
      if (isRecharge(record)) {
        item.recharged += Number(record.credits ?? 0);
      } else {
        item.consumed += Number(record.credits ?? 0);
      }
      grouped.set(key, item);
    });
    return [...grouped.values()].sort((a, b) => a.day.localeCompare(b.day));
  }, [filteredRecords]);

  const categoryData = useMemo(() => {
    const grouped = new Map<string, { name: string; value: number; color: string }>();
    filteredRecords.filter((record) => !isRecharge(record)).forEach((record) => {
      const meta = getMeta(record.operation);
      const item = grouped.get(meta.category) ?? { name: meta.category, value: 0, color: meta.color };
      item.value += Number(record.credits ?? 0);
      grouped.set(meta.category, item);
    });
    return [...grouped.values()].sort((a, b) => b.value - a.value);
  }, [filteredRecords]);

  const operationOptions = useMemo(() => {
    const operations = new Set(records.map((record) => record.operation).filter(Boolean));
    return [...operations].sort();
  }, [records]);

  const remainingCredits = Number(balance?.balance ?? 0);
  const usedCredits = Number(balance?.totalSpent ?? 0);
  const totalRecharged = Number(balance?.totalRecharged ?? 0);
  const selectedPackageInfo = PACKAGES.find((pkg) => pkg.id === selectedPackage) ?? PACKAGES[2];

  return (
    <>
      <div className="h-full overflow-auto bg-background p-6">
        <div className="mx-auto max-w-7xl">
          <div className="mb-6 flex items-center justify-between gap-4">
            <div>
              <h1 className="mb-1 text-2xl font-semibold text-foreground">用量与积分明细</h1>
              <p className="text-sm text-muted-foreground">查看余额、充值、模型调用和每次积分变动。</p>
            </div>
            <button
              onClick={() => {
                setShowPurchaseModal(true);
                setPurchased(false);
              }}
              className="flex items-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm text-primary-foreground transition-colors hover:bg-primary/90"
            >
              <PackagePlus className="h-4 w-4" />
              购买积分
            </button>
          </div>

          <div className="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-4">
            <StatCard
              label="当前余额"
              value={money(remainingCredits)}
              caption={`累计充值 ${money(totalRecharged)} 积分`}
              icon={WalletCards}
              tone="bg-primary/10 text-primary"
            />
            <StatCard
              label="累计消费"
              value={money(usedCredits)}
              caption={`共 ${totalRecords} 条账单记录`}
              icon={TrendingDown}
              tone="bg-red-50 text-red-600"
            />
            <StatCard
              label="本页消费"
              value={money(pageStats.consumed)}
              caption={`主要消耗：${pageStats.topCategory}`}
              icon={CircleDollarSign}
              tone="bg-amber-50 text-amber-600"
            />
            <StatCard
              label="本页充值 / 失败"
              value={`${money(pageStats.recharged)} / ${pageStats.failed}`}
              caption={`第 ${page + 1} 页，共 ${pageCount} 页`}
              icon={AlertCircle}
              tone="bg-slate-100 text-slate-600"
            />
          </div>

          <div className="mb-6 rounded-xl border border-border bg-card p-4">
            <div className="mb-4 flex items-center gap-2">
              <Filter className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium text-foreground">筛选当前页记录</span>
              <span className="text-xs text-muted-foreground">后端分页已加载 {records.length} 条</span>
            </div>

            <div className="mb-4 flex flex-wrap gap-2">
              {[
                ["all", "全部"],
                ["consume", "只看消费"],
                ["recharge", "只看充值"],
                ["failed", "失败记录"],
              ].map(([value, label]) => (
                <button
                  key={value}
                  onClick={() => setQuickFilter(value as QuickFilter)}
                  className={`rounded-lg border px-3 py-1.5 text-sm transition-colors ${
                    quickFilter === value
                      ? "border-primary bg-primary text-primary-foreground"
                      : "border-border bg-background text-muted-foreground hover:text-foreground"
                  }`}
                >
                  {label}
                </button>
              ))}
            </div>

            <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
              <label className="block">
                <span className="mb-2 block text-xs text-muted-foreground">开始日期</span>
                <div className="relative">
                  <Calendar className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <input
                    type="date"
                    value={dateRange.start}
                    onChange={(event) => setDateRange({ ...dateRange, start: event.target.value })}
                    className="w-full rounded-lg border border-border bg-background py-2 pl-9 pr-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </label>

              <label className="block">
                <span className="mb-2 block text-xs text-muted-foreground">结束日期</span>
                <div className="relative">
                  <Calendar className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <input
                    type="date"
                    value={dateRange.end}
                    onChange={(event) => setDateRange({ ...dateRange, end: event.target.value })}
                    className="w-full rounded-lg border border-border bg-background py-2 pl-9 pr-3 text-sm text-foreground outline-none focus:ring-2 focus:ring-primary/20"
                  />
                </div>
              </label>

              <label className="block">
                <span className="mb-2 block text-xs text-muted-foreground">操作类型</span>
                <select
                  value={selectedType}
                  onChange={(event) => {
                    setSelectedType(event.target.value);
                    setPage(0);
                  }}
                  className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none focus:ring-2 focus:ring-primary/20"
                >
                  <option value="">全部操作</option>
                  {operationOptions.map((operation) => (
                    <option key={operation} value={operation}>
                      {getMeta(operation).label}
                    </option>
                  ))}
                </select>
              </label>
            </div>
          </div>

          <div className="mb-6 grid grid-cols-1 gap-4 xl:grid-cols-[1.4fr_0.8fr]">
            <div className="rounded-xl border border-border bg-card p-5">
              <div className="mb-5">
                <h2 className="font-medium text-foreground">本页积分走势</h2>
                <p className="mt-1 text-xs text-muted-foreground">根据当前筛选后的真实账单记录聚合。</p>
              </div>
              <div className="h-72">
                {dailyData.length === 0 ? (
                  <EmptyState />
                ) : (
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={dailyData} margin={{ top: 8, right: 8, left: 0, bottom: 0 }}>
                      <CartesianGrid stroke="#e5e7eb" strokeDasharray="3 3" />
                      <XAxis dataKey="day" tick={{ fill: "#6b7280", fontSize: 12 }} stroke="#9ca3af" />
                      <YAxis tick={{ fill: "#6b7280", fontSize: 12 }} stroke="#9ca3af" tickFormatter={(v) => `${v}`} />
                      <Tooltip
                        contentStyle={{ border: "1px solid #e5e7eb", borderRadius: 8, fontSize: 12 }}
                        formatter={(value: number, name: string) => [
                          `${value.toLocaleString()} 积分`,
                          name === "consumed" ? "消费" : "充值",
                        ]}
                      />
                      <Bar dataKey="consumed" name="消费" fill="#ef4444" radius={[4, 4, 0, 0]} />
                      <Bar dataKey="recharged" name="充值" fill="#22c55e" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                )}
              </div>
            </div>

            <div className="rounded-xl border border-border bg-card p-5">
              <div className="mb-5">
                <h2 className="font-medium text-foreground">消耗结构</h2>
                <p className="mt-1 text-xs text-muted-foreground">按剧本、图片、视频等类型汇总。</p>
              </div>
              <div className="h-72">
                {categoryData.length === 0 ? (
                  <EmptyState />
                ) : (
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie data={categoryData} dataKey="value" nameKey="name" innerRadius={54} outerRadius={88} paddingAngle={3}>
                        {categoryData.map((entry) => (
                          <Cell key={entry.name} fill={entry.color} />
                        ))}
                      </Pie>
                      <Tooltip formatter={(value: number, name: string) => [`${value.toLocaleString()} 积分`, name]} />
                    </PieChart>
                  </ResponsiveContainer>
                )}
              </div>
              <div className="mt-2 grid grid-cols-2 gap-2">
                {categoryData.slice(0, 4).map((item) => (
                  <div key={item.name} className="flex items-center gap-2 text-xs text-muted-foreground">
                    <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: item.color }} />
                    <span>{item.name}</span>
                    <span className="ml-auto text-foreground">{money(item.value)}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="overflow-hidden rounded-xl border border-border bg-card">
            <div className="flex items-center justify-between border-b border-border p-4">
              <div>
                <h2 className="font-medium text-foreground">账单明细</h2>
                <p className="mt-1 text-xs text-muted-foreground">消费为负数，充值为正数；失败记录通常为 0 积分。</p>
              </div>
              {isLoading && <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
            </div>

            <div className="overflow-x-auto">
              <table className="w-full min-w-[920px]">
                <thead className="bg-muted/50">
                  <tr>
                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground">操作</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground">模型 / 类型</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground">项目 / 引用</th>
                    <th className="px-4 py-3 text-right text-xs font-medium text-muted-foreground">积分变动</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground">状态</th>
                    <th className="px-4 py-3 text-left text-xs font-medium text-muted-foreground">时间</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {filteredRecords.length === 0 && (
                    <tr>
                      <td colSpan={6}>
                        <EmptyState />
                      </td>
                    </tr>
                  )}

                  {filteredRecords.map((record) => {
                    const meta = getMeta(record.operation);
                    const Icon = meta.icon;
                    const recharge = isRecharge(record);
                    const success = isSuccess(record);
                    const modelText = record.modelName || record.modelId || record.modelProvider || record.modality || "-";
                    return (
                      <tr key={record.id} className="transition-colors hover:bg-muted/30">
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-3">
                            <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-muted">
                              <Icon className="h-4 w-4" style={{ color: meta.color }} />
                            </div>
                            <div>
                              <div className="text-sm font-medium text-foreground">{meta.label}</div>
                              <div className="text-xs text-muted-foreground">{meta.category}</div>
                            </div>
                          </div>
                        </td>
                        <td className="px-4 py-3">
                          <div className="text-sm text-foreground">{modelText}</div>
                          <div className="text-xs text-muted-foreground">
                            {record.unitCount ? `${record.unitCount} 单元` : record.billingMode || "-"}
                          </div>
                        </td>
                        <td className="px-4 py-3">
                          <div className="text-sm text-foreground">{record.projectName || (record.projectId ? `项目 ${record.projectId}` : "-")}</div>
                          <div className="max-w-[220px] truncate text-xs text-muted-foreground">引用 {record.refId ?? "-"}</div>
                        </td>
                        <td className="px-4 py-3 text-right">
                          <span className={`text-sm font-semibold ${recharge ? "text-emerald-600" : "text-red-600"}`}>
                            {recharge ? "+" : "-"}
                            {money(record.credits)}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <span
                            className={`inline-flex items-center gap-1 rounded-full px-2 py-1 text-xs ${
                              success ? "bg-emerald-50 text-emerald-700" : "bg-red-50 text-red-700"
                            }`}
                          >
                            {success ? <Check className="h-3 w-3" /> : <AlertCircle className="h-3 w-3" />}
                            {success ? "成功" : "失败"}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-sm text-muted-foreground">{formatDateTime(record.createdAt)}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            <div className="flex items-center justify-between border-t border-border p-4">
              <div className="text-xs text-muted-foreground">
                当前显示 {filteredRecords.length} 条，全部账单 {totalRecords} 条
              </div>
              <div className="flex items-center gap-2">
                <button
                  disabled={page === 0}
                  onClick={() => setPage((value) => Math.max(0, value - 1))}
                  className="inline-flex items-center gap-1 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-muted disabled:opacity-40"
                >
                  <ChevronLeft className="h-4 w-4" />
                  上一页
                </button>
                <span className="px-2 text-sm text-muted-foreground">
                  {page + 1} / {pageCount}
                </span>
                <button
                  disabled={(page + 1) * PAGE_SIZE >= totalRecords}
                  onClick={() => setPage((value) => value + 1)}
                  className="inline-flex items-center gap-1 rounded-lg border border-border bg-card px-3 py-1.5 text-sm text-foreground transition-colors hover:bg-muted disabled:opacity-40"
                >
                  下一页
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {showPurchaseModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6 backdrop-blur-sm">
          <div className="w-full max-w-2xl rounded-2xl border border-border bg-card p-6">
            <div className="mb-6 flex items-center justify-between">
              <div>
                <h2 className="text-xl font-semibold text-foreground">购买积分资源包</h2>
                <p className="mt-1 text-sm text-muted-foreground">演示环境会直接到账，线上版本可接支付或运营后台充值。</p>
              </div>
              <button onClick={() => setShowPurchaseModal(false)} className="rounded-lg p-2 transition-colors hover:bg-muted">
                <X className="h-5 w-5 text-muted-foreground" />
              </button>
            </div>

            {purchased ? (
              <div className="py-12 text-center">
                <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100">
                  <Check className="h-8 w-8 text-emerald-600" />
                </div>
                <h3 className="mb-2 text-lg font-semibold text-foreground">购买成功</h3>
                <p className="mb-6 text-sm text-muted-foreground">{selectedPackageInfo.credits.toLocaleString()} 积分已到账。</p>
                <button
                  onClick={() => setShowPurchaseModal(false)}
                  className="rounded-lg bg-primary px-6 py-2.5 text-sm text-primary-foreground transition-colors hover:bg-primary/90"
                >
                  完成
                </button>
              </div>
            ) : (
              <>
                <div className="mb-6 grid grid-cols-1 gap-3 sm:grid-cols-2">
                  {PACKAGES.map((pkg) => (
                    <button
                      key={pkg.id}
                      onClick={() => setSelectedPackage(pkg.id)}
                      className={`rounded-xl border-2 p-4 text-left transition-all ${
                        selectedPackage === pkg.id
                          ? "border-primary bg-primary/5"
                          : "border-border bg-background hover:border-primary/40"
                      }`}
                    >
                      <div className="mb-2 flex items-center justify-between">
                        <span className="font-semibold text-foreground">{pkg.label}</span>
                        {pkg.id === "pro" && (
                          <span className="rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground">推荐</span>
                        )}
                      </div>
                      <div className="mb-1 text-2xl font-bold text-primary">
                        {pkg.credits.toLocaleString()} <span className="text-sm font-normal text-muted-foreground">积分</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-xs text-muted-foreground">{pkg.desc}</span>
                        <span className="text-lg font-semibold text-foreground">{pkg.price}</span>
                      </div>
                    </button>
                  ))}
                </div>

                <div className="mb-6 flex items-center gap-3 rounded-xl bg-muted p-4">
                  <Sparkles className="h-5 w-5 flex-shrink-0 text-primary" />
                  <div className="text-sm text-muted-foreground">
                    当前余额：
                    <span className="font-semibold text-foreground">{money(remainingCredits)}</span>
                    {" 积分，购买后变为 "}
                    <span className="font-semibold text-foreground">{money(remainingCredits + selectedPackageInfo.credits)}</span>
                    {" 积分"}
                  </div>
                </div>

                <div className="flex gap-3">
                  <button
                    onClick={() => setShowPurchaseModal(false)}
                    className="flex-1 rounded-lg border border-border bg-card py-2.5 text-sm text-foreground transition-colors hover:bg-muted"
                  >
                    取消
                  </button>
                  <button
                    onClick={async () => {
                      await purchase.mutateAsync(selectedPackage);
                      setPurchased(true);
                    }}
                    disabled={purchase.isPending}
                    className="flex flex-1 items-center justify-center gap-2 rounded-lg bg-primary py-2.5 text-sm text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-70"
                  >
                    {purchase.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <PackagePlus className="h-4 w-4" />}
                    确认购买 {selectedPackageInfo.price}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </>
  );
}
