import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { 
  Wallet, Plus, Edit, Trash2, Search, ArrowUpRight, ArrowDownLeft, 
  RefreshCcw, Gift, DollarSign, Users, TrendingUp, History, BarChart3
} from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line, Legend } from "recharts";

interface RechargePlan {
  id: string;
  name: string;
  description: string | null;
  recharge_amount: number;
  bonus_amount: number;
  is_active: boolean;
  display_order: number;
  created_at: string;
}

interface UserBalance {
  id: string;
  user_id: string;
  balance: number;
  total_recharged: number;
  total_bonus: number;
  total_consumed: number;
  created_at: string;
  profile?: {
    display_name: string | null;
    phone: string | null;
  };
}

interface BalanceTransaction {
  id: string;
  user_id: string;
  type: string;
  amount: number;
  balance_before: number;
  balance_after: number;
  description: string | null;
  created_at: string;
  profile?: {
    display_name: string | null;
  };
}

// 图表颜色
const CHART_COLORS = ['hsl(var(--primary))', 'hsl(142, 76%, 36%)', 'hsl(38, 92%, 50%)', 'hsl(280, 65%, 60%)', 'hsl(199, 89%, 48%)'];

export function MembershipManager() {
  const [activeTab, setActiveTab] = useState("analytics");
  const [plans, setPlans] = useState<RechargePlan[]>([]);
  const [balances, setBalances] = useState<UserBalance[]>([]);
  const [transactions, setTransactions] = useState<BalanceTransaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  
  // 统计数据
  const [stats, setStats] = useState({
    totalBalance: 0,
    totalUsers: 0,
    totalRecharged: 0,
    totalConsumed: 0
  });

  // 分析数据
  const [analyticsData, setAnalyticsData] = useState<{
    dailyTrend: { date: string; recharge: number; consume: number; count: number }[];
    balanceDistribution: { range: string; count: number }[];
    topUsers: { name: string; balance: number; recharged: number }[];
    transactionTypes: { type: string; amount: number; count: number }[];
  }>({
    dailyTrend: [],
    balanceDistribution: [],
    topUsers: [],
    transactionTypes: []
  });

  // 方案编辑状态
  const [editingPlan, setEditingPlan] = useState<RechargePlan | null>(null);
  const [planDialogOpen, setPlanDialogOpen] = useState(false);
  const [planForm, setPlanForm] = useState({
    name: "",
    description: "",
    recharge_amount: 0,
    bonus_amount: 0,
    is_active: true,
    display_order: 0
  });

  // 充值操作状态
  const [rechargeDialogOpen, setRechargeDialogOpen] = useState(false);
  const [rechargeForm, setRechargeForm] = useState({
    user_id: "",
    amount: 0,
    bonus: 0,
    description: ""
  });

  useEffect(() => {
    fetchData();
  }, [activeTab]);

  const fetchData = async () => {
    setLoading(true);
    try {
      if (activeTab === "analytics") {
        await fetchAnalytics();
      } else if (activeTab === "plans") {
        await fetchPlans();
      } else if (activeTab === "balances") {
        await fetchBalances();
      } else if (activeTab === "transactions") {
        await fetchTransactions();
      }
      await fetchStats();
    } catch (error) {
      console.error("获取数据失败:", error);
      toast.error("获取数据失败");
    } finally {
      setLoading(false);
    }
  };

  const fetchAnalytics = async () => {
    // 获取最近30天的交易数据
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const { data: txData } = await supabase
      .from("balance_transactions")
      .select("*")
      .gte("created_at", thirtyDaysAgo.toISOString())
      .order("created_at", { ascending: true });

    // 获取余额分布数据
    const { data: balanceData } = await supabase
      .from("user_balances")
      .select("*")
      .order("balance", { ascending: false });

    // 获取用户信息用于top用户
    let topUsersData: { name: string; balance: number; recharged: number }[] = [];
    if (balanceData && balanceData.length > 0) {
      const topBalances = balanceData.slice(0, 10);
      const userIds = topBalances.map(b => b.user_id);
      const { data: profiles } = await supabase
        .from("profiles")
        .select("user_id, display_name")
        .in("user_id", userIds);
      
      topUsersData = topBalances.map(b => ({
        name: profiles?.find(p => p.user_id === b.user_id)?.display_name || "未知用户",
        balance: Number(b.balance),
        recharged: Number(b.total_recharged)
      }));
    }

    // 处理日趋势数据
    const dailyMap = new Map<string, { recharge: number; consume: number; count: number }>();
    txData?.forEach(tx => {
      const date = new Date(tx.created_at).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
      const existing = dailyMap.get(date) || { recharge: 0, consume: 0, count: 0 };
      if (tx.type === 'recharge' || tx.type === 'bonus') {
        existing.recharge += Number(tx.amount);
      } else if (tx.type === 'consume') {
        existing.consume += Math.abs(Number(tx.amount));
      }
      existing.count += 1;
      dailyMap.set(date, existing);
    });
    const dailyTrend = Array.from(dailyMap.entries()).map(([date, data]) => ({ date, ...data }));

    // 余额分布
    const ranges = [
      { min: 0, max: 100, label: '0-100' },
      { min: 100, max: 500, label: '100-500' },
      { min: 500, max: 1000, label: '500-1000' },
      { min: 1000, max: 5000, label: '1000-5000' },
      { min: 5000, max: Infinity, label: '5000+' }
    ];
    const balanceDistribution = ranges.map(r => ({
      range: r.label,
      count: balanceData?.filter(b => Number(b.balance) >= r.min && Number(b.balance) < r.max).length || 0
    }));

    // 交易类型统计
    const typeMap = new Map<string, { amount: number; count: number }>();
    txData?.forEach(tx => {
      const existing = typeMap.get(tx.type) || { amount: 0, count: 0 };
      existing.amount += Math.abs(Number(tx.amount));
      existing.count += 1;
      typeMap.set(tx.type, existing);
    });
    const typeLabels: Record<string, string> = {
      recharge: '充值',
      bonus: '赠送',
      consume: '消费',
      refund: '退款'
    };
    const transactionTypes = Array.from(typeMap.entries()).map(([type, data]) => ({
      type: typeLabels[type] || type,
      ...data
    }));

    setAnalyticsData({
      dailyTrend,
      balanceDistribution,
      topUsers: topUsersData,
      transactionTypes
    });
  };

  const fetchPlans = async () => {
    const { data, error } = await supabase
      .from("recharge_plans")
      .select("*")
      .order("display_order", { ascending: true });
    
    if (error) throw error;
    setPlans(data || []);
  };

  const fetchBalances = async () => {
    const { data, error } = await supabase
      .from("user_balances")
      .select("*")
      .order("balance", { ascending: false });
    
    if (error) throw error;
    
    // 获取用户信息
    if (data && data.length > 0) {
      const userIds = data.map(b => b.user_id);
      const { data: profiles } = await supabase
        .from("profiles")
        .select("user_id, display_name, phone")
        .in("user_id", userIds);
      
      const balancesWithProfiles = data.map(b => ({
        ...b,
        profile: profiles?.find(p => p.user_id === b.user_id)
      }));
      setBalances(balancesWithProfiles);
    } else {
      setBalances([]);
    }
  };

  const fetchTransactions = async () => {
    const { data, error } = await supabase
      .from("balance_transactions")
      .select("*")
      .order("created_at", { ascending: false })
      .limit(100);
    
    if (error) throw error;
    
    // 获取用户信息
    if (data && data.length > 0) {
      const userIds = [...new Set(data.map(t => t.user_id))];
      const { data: profiles } = await supabase
        .from("profiles")
        .select("user_id, display_name")
        .in("user_id", userIds);
      
      const transactionsWithProfiles = data.map(t => ({
        ...t,
        profile: profiles?.find(p => p.user_id === t.user_id)
      }));
      setTransactions(transactionsWithProfiles);
    } else {
      setTransactions([]);
    }
  };

  const fetchStats = async () => {
    const { data, error } = await supabase
      .from("user_balances")
      .select("balance, total_recharged, total_consumed");
    
    if (!error && data) {
      setStats({
        totalBalance: data.reduce((sum, b) => sum + Number(b.balance), 0),
        totalUsers: data.length,
        totalRecharged: data.reduce((sum, b) => sum + Number(b.total_recharged), 0),
        totalConsumed: data.reduce((sum, b) => sum + Number(b.total_consumed), 0)
      });
    }
  };

  const handleSavePlan = async () => {
    try {
      if (editingPlan) {
        const { error } = await supabase
          .from("recharge_plans")
          .update(planForm)
          .eq("id", editingPlan.id);
        
        if (error) throw error;
        toast.success("储值方案更新成功");
      } else {
        const { error } = await supabase
          .from("recharge_plans")
          .insert([planForm]);
        
        if (error) throw error;
        toast.success("储值方案创建成功");
      }
      
      setPlanDialogOpen(false);
      setEditingPlan(null);
      resetPlanForm();
      fetchPlans();
    } catch (error) {
      console.error("保存方案失败:", error);
      toast.error("保存方案失败");
    }
  };

  const handleDeletePlan = async (id: string) => {
    if (!confirm("确定要删除这个储值方案吗？")) return;
    
    try {
      const { error } = await supabase
        .from("recharge_plans")
        .delete()
        .eq("id", id);
      
      if (error) throw error;
      toast.success("储值方案已删除");
      fetchPlans();
    } catch (error) {
      console.error("删除方案失败:", error);
      toast.error("删除方案失败");
    }
  };

  const handleEditPlan = (plan: RechargePlan) => {
    setEditingPlan(plan);
    setPlanForm({
      name: plan.name,
      description: plan.description || "",
      recharge_amount: plan.recharge_amount,
      bonus_amount: plan.bonus_amount,
      is_active: plan.is_active,
      display_order: plan.display_order
    });
    setPlanDialogOpen(true);
  };

  const resetPlanForm = () => {
    setPlanForm({
      name: "",
      description: "",
      recharge_amount: 0,
      bonus_amount: 0,
      is_active: true,
      display_order: 0
    });
  };

  const handleManualRecharge = async () => {
    if (!rechargeForm.user_id || rechargeForm.amount <= 0) {
      toast.error("请填写正确的充值信息");
      return;
    }

    try {
      // 获取当前余额
      let { data: currentBalance } = await supabase
        .from("user_balances")
        .select("*")
        .eq("user_id", rechargeForm.user_id)
        .single();

      const balanceBefore = currentBalance?.balance || 0;
      const totalAmount = rechargeForm.amount + rechargeForm.bonus;
      const balanceAfter = balanceBefore + totalAmount;

      // 更新或创建余额记录
      if (currentBalance) {
        await supabase
          .from("user_balances")
          .update({
            balance: balanceAfter,
            total_recharged: Number(currentBalance.total_recharged) + rechargeForm.amount,
            total_bonus: Number(currentBalance.total_bonus) + rechargeForm.bonus
          })
          .eq("user_id", rechargeForm.user_id);
      } else {
        await supabase
          .from("user_balances")
          .insert([{
            user_id: rechargeForm.user_id,
            balance: balanceAfter,
            total_recharged: rechargeForm.amount,
            total_bonus: rechargeForm.bonus
          }]);
      }

      // 创建交易记录
      await supabase
        .from("balance_transactions")
        .insert([{
          user_id: rechargeForm.user_id,
          type: "recharge",
          amount: totalAmount,
          balance_before: balanceBefore,
          balance_after: balanceAfter,
          description: rechargeForm.description || `手动充值 ¥${rechargeForm.amount}${rechargeForm.bonus > 0 ? ` + 赠送 ¥${rechargeForm.bonus}` : ''}`
        }]);

      toast.success("充值成功");
      setRechargeDialogOpen(false);
      setRechargeForm({ user_id: "", amount: 0, bonus: 0, description: "" });
      fetchData();
    } catch (error) {
      console.error("充值失败:", error);
      toast.error("充值失败");
    }
  };

  const getTransactionTypeLabel = (type: string) => {
    const labels: Record<string, { text: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
      recharge: { text: "充值", variant: "default" },
      bonus: { text: "赠送", variant: "secondary" },
      consume: { text: "消费", variant: "destructive" },
      refund: { text: "退款", variant: "outline" }
    };
    return labels[type] || { text: type, variant: "default" as const };
  };

  const filteredBalances = balances.filter(b => 
    !searchTerm || 
    b.profile?.display_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    b.profile?.phone?.includes(searchTerm)
  );

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold mb-1 border-l-4 border-primary pl-3">会员储值管理</h2>
        <p className="text-muted-foreground text-sm pl-4">管理储值方案、会员余额和交易记录</p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">总余额</p>
                <p className="text-2xl font-bold">¥{stats.totalBalance.toFixed(2)}</p>
              </div>
              <Wallet className="h-8 w-8 text-primary opacity-80" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">储值会员数</p>
                <p className="text-2xl font-bold">{stats.totalUsers}</p>
              </div>
              <Users className="h-8 w-8 text-blue-500 opacity-80" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">总充值金额</p>
                <p className="text-2xl font-bold">¥{stats.totalRecharged.toFixed(2)}</p>
              </div>
              <TrendingUp className="h-8 w-8 text-green-500 opacity-80" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">总消费金额</p>
                <p className="text-2xl font-bold">¥{stats.totalConsumed.toFixed(2)}</p>
              </div>
              <DollarSign className="h-8 w-8 text-orange-500 opacity-80" />
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList>
          <TabsTrigger value="analytics" className="flex items-center gap-2">
            <BarChart3 className="h-4 w-4" />
            数据分析
          </TabsTrigger>
          <TabsTrigger value="plans" className="flex items-center gap-2">
            <Gift className="h-4 w-4" />
            储值方案
          </TabsTrigger>
          <TabsTrigger value="balances" className="flex items-center gap-2">
            <Wallet className="h-4 w-4" />
            会员余额
          </TabsTrigger>
          <TabsTrigger value="transactions" className="flex items-center gap-2">
            <History className="h-4 w-4" />
            交易记录
          </TabsTrigger>
        </TabsList>

        {/* 数据分析 */}
        <TabsContent value="analytics" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 充值消费趋势 */}
            <Card className="lg:col-span-2">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <TrendingUp className="h-5 w-5" />
                  近30天充值消费趋势
                </CardTitle>
                <CardDescription>展示每日充值和消费金额变化</CardDescription>
              </CardHeader>
              <CardContent>
                {analyticsData.dailyTrend.length > 0 ? (
                  <ResponsiveContainer width="100%" height={300}>
                    <LineChart data={analyticsData.dailyTrend}>
                      <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                      <XAxis dataKey="date" className="text-xs" />
                      <YAxis className="text-xs" />
                      <Tooltip 
                        contentStyle={{ 
                          backgroundColor: 'hsl(var(--card))', 
                          border: '1px solid hsl(var(--border))',
                          borderRadius: '8px'
                        }}
                        formatter={(value: number) => [`¥${value.toFixed(2)}`, '']}
                      />
                      <Legend />
                      <Line 
                        type="monotone" 
                        dataKey="recharge" 
                        name="充值金额" 
                        stroke="hsl(142, 76%, 36%)" 
                        strokeWidth={2}
                        dot={{ fill: 'hsl(142, 76%, 36%)' }}
                      />
                      <Line 
                        type="monotone" 
                        dataKey="consume" 
                        name="消费金额" 
                        stroke="hsl(38, 92%, 50%)" 
                        strokeWidth={2}
                        dot={{ fill: 'hsl(38, 92%, 50%)' }}
                      />
                    </LineChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                    暂无趋势数据
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 余额分布 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Wallet className="h-5 w-5" />
                  会员余额分布
                </CardTitle>
                <CardDescription>按余额区间统计会员数量</CardDescription>
              </CardHeader>
              <CardContent>
                {analyticsData.balanceDistribution.some(d => d.count > 0) ? (
                  <ResponsiveContainer width="100%" height={280}>
                    <BarChart data={analyticsData.balanceDistribution}>
                      <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                      <XAxis dataKey="range" className="text-xs" />
                      <YAxis className="text-xs" />
                      <Tooltip 
                        contentStyle={{ 
                          backgroundColor: 'hsl(var(--card))', 
                          border: '1px solid hsl(var(--border))',
                          borderRadius: '8px'
                        }}
                        formatter={(value: number) => [`${value} 人`, '会员数']}
                      />
                      <Bar dataKey="count" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-[280px] flex items-center justify-center text-muted-foreground">
                    暂无余额数据
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 交易类型分布 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <History className="h-5 w-5" />
                  交易类型分布
                </CardTitle>
                <CardDescription>近30天各类交易占比</CardDescription>
              </CardHeader>
              <CardContent>
                {analyticsData.transactionTypes.length > 0 ? (
                  <ResponsiveContainer width="100%" height={280}>
                    <PieChart>
                      <Pie
                        data={analyticsData.transactionTypes}
                        cx="50%"
                        cy="50%"
                        innerRadius={60}
                        outerRadius={100}
                        paddingAngle={2}
                        dataKey="amount"
                        nameKey="type"
                        label={({ type, percent }) => `${type} ${(percent * 100).toFixed(0)}%`}
                      >
                        {analyticsData.transactionTypes.map((_, index) => (
                          <Cell key={`cell-${index}`} fill={CHART_COLORS[index % CHART_COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip 
                        contentStyle={{ 
                          backgroundColor: 'hsl(var(--card))', 
                          border: '1px solid hsl(var(--border))',
                          borderRadius: '8px'
                        }}
                        formatter={(value: number) => [`¥${value.toFixed(2)}`, '金额']}
                      />
                    </PieChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-[280px] flex items-center justify-center text-muted-foreground">
                    暂无交易数据
                  </div>
                )}
              </CardContent>
            </Card>

            {/* TOP会员 */}
            <Card className="lg:col-span-2">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Users className="h-5 w-5" />
                  储值TOP10会员
                </CardTitle>
                <CardDescription>余额最高的会员排行</CardDescription>
              </CardHeader>
              <CardContent>
                {analyticsData.topUsers.length > 0 ? (
                  <ResponsiveContainer width="100%" height={300}>
                    <BarChart data={analyticsData.topUsers} layout="vertical">
                      <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                      <XAxis type="number" className="text-xs" />
                      <YAxis type="category" dataKey="name" width={100} className="text-xs" />
                      <Tooltip 
                        contentStyle={{ 
                          backgroundColor: 'hsl(var(--card))', 
                          border: '1px solid hsl(var(--border))',
                          borderRadius: '8px'
                        }}
                        formatter={(value: number) => [`¥${value.toFixed(2)}`, '']}
                      />
                      <Legend />
                      <Bar dataKey="balance" name="当前余额" fill="hsl(var(--primary))" radius={[0, 4, 4, 0]} />
                      <Bar dataKey="recharged" name="累计充值" fill="hsl(142, 76%, 36%)" radius={[0, 4, 4, 0]} />
                    </BarChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-[300px] flex items-center justify-center text-muted-foreground">
                    暂无会员数据
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* 储值方案 */}
        <TabsContent value="plans" className="space-y-4">
          <div className="flex justify-between items-center">
            <p className="text-sm text-muted-foreground">设置不同面额的储值方案，吸引顾客充值消费</p>
            <Dialog open={planDialogOpen} onOpenChange={setPlanDialogOpen}>
              <DialogTrigger asChild>
                <Button onClick={() => { setEditingPlan(null); resetPlanForm(); }}>
                  <Plus className="h-4 w-4 mr-2" />
                  新增方案
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>{editingPlan ? "编辑储值方案" : "新增储值方案"}</DialogTitle>
                  <DialogDescription>设置储值金额和赠送金额</DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label>方案名称</Label>
                    <Input 
                      value={planForm.name}
                      onChange={e => setPlanForm(prev => ({ ...prev, name: e.target.value }))}
                      placeholder="如：充100送10"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>方案描述</Label>
                    <Input 
                      value={planForm.description}
                      onChange={e => setPlanForm(prev => ({ ...prev, description: e.target.value }))}
                      placeholder="可选描述"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>充值金额 (元)</Label>
                      <Input 
                        type="number"
                        value={planForm.recharge_amount}
                        onChange={e => setPlanForm(prev => ({ ...prev, recharge_amount: Number(e.target.value) }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>赠送金额 (元)</Label>
                      <Input 
                        type="number"
                        value={planForm.bonus_amount}
                        onChange={e => setPlanForm(prev => ({ ...prev, bonus_amount: Number(e.target.value) }))}
                      />
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>排序</Label>
                      <Input 
                        type="number"
                        value={planForm.display_order}
                        onChange={e => setPlanForm(prev => ({ ...prev, display_order: Number(e.target.value) }))}
                      />
                    </div>
                    <div className="flex items-center space-x-2 pt-6">
                      <Switch 
                        checked={planForm.is_active}
                        onCheckedChange={checked => setPlanForm(prev => ({ ...prev, is_active: checked }))}
                      />
                      <Label>启用</Label>
                    </div>
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setPlanDialogOpen(false)}>取消</Button>
                  <Button onClick={handleSavePlan}>保存</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {plans.map(plan => (
              <Card key={plan.id} className={!plan.is_active ? "opacity-60" : ""}>
                <CardHeader className="pb-2">
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-lg">{plan.name}</CardTitle>
                    <Badge variant={plan.is_active ? "default" : "secondary"}>
                      {plan.is_active ? "启用" : "停用"}
                    </Badge>
                  </div>
                  {plan.description && (
                    <CardDescription>{plan.description}</CardDescription>
                  )}
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <div className="flex items-baseline gap-1">
                      <span className="text-3xl font-bold text-primary">¥{plan.recharge_amount}</span>
                      {plan.bonus_amount > 0 && (
                        <span className="text-lg text-green-600">+¥{plan.bonus_amount}</span>
                      )}
                    </div>
                    {plan.bonus_amount > 0 && (
                      <p className="text-sm text-muted-foreground">
                        实际到账 ¥{plan.recharge_amount + plan.bonus_amount}
                      </p>
                    )}
                    <div className="flex gap-2 pt-2">
                      <Button variant="outline" size="sm" className="flex-1" onClick={() => handleEditPlan(plan)}>
                        <Edit className="h-4 w-4 mr-1" />
                        编辑
                      </Button>
                      <Button variant="outline" size="sm" className="text-destructive" onClick={() => handleDeletePlan(plan.id)}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
            {plans.length === 0 && !loading && (
              <div className="col-span-full text-center py-12 text-muted-foreground">
                <Gift className="h-12 w-12 mx-auto mb-3 opacity-50" />
                <p>暂无储值方案</p>
                <p className="text-sm">点击"新增方案"创建第一个储值方案</p>
              </div>
            )}
          </div>
        </TabsContent>

        {/* 会员余额 */}
        <TabsContent value="balances" className="space-y-4">
          <div className="flex justify-between items-center gap-4">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input 
                placeholder="搜索会员..."
                value={searchTerm}
                onChange={e => setSearchTerm(e.target.value)}
                className="pl-9"
              />
            </div>
            <Dialog open={rechargeDialogOpen} onOpenChange={setRechargeDialogOpen}>
              <DialogTrigger asChild>
                <Button>
                  <ArrowUpRight className="h-4 w-4 mr-2" />
                  手动充值
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>手动充值</DialogTitle>
                  <DialogDescription>为会员手动添加余额</DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label>用户ID</Label>
                    <Input 
                      value={rechargeForm.user_id}
                      onChange={e => setRechargeForm(prev => ({ ...prev, user_id: e.target.value }))}
                      placeholder="输入用户UUID"
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>充值金额 (元)</Label>
                      <Input 
                        type="number"
                        value={rechargeForm.amount}
                        onChange={e => setRechargeForm(prev => ({ ...prev, amount: Number(e.target.value) }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>赠送金额 (元)</Label>
                      <Input 
                        type="number"
                        value={rechargeForm.bonus}
                        onChange={e => setRechargeForm(prev => ({ ...prev, bonus: Number(e.target.value) }))}
                      />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label>备注</Label>
                    <Input 
                      value={rechargeForm.description}
                      onChange={e => setRechargeForm(prev => ({ ...prev, description: e.target.value }))}
                      placeholder="可选"
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setRechargeDialogOpen(false)}>取消</Button>
                  <Button onClick={handleManualRecharge}>确认充值</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>

          <Card>
            <ScrollArea className="h-[500px]">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>会员</TableHead>
                    <TableHead className="text-right">当前余额</TableHead>
                    <TableHead className="text-right">累计充值</TableHead>
                    <TableHead className="text-right">累计赠送</TableHead>
                    <TableHead className="text-right">累计消费</TableHead>
                    <TableHead>开通时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredBalances.map(balance => (
                    <TableRow key={balance.id}>
                      <TableCell>
                        <div>
                          <p className="font-medium">{balance.profile?.display_name || "未知用户"}</p>
                          <p className="text-sm text-muted-foreground">{balance.profile?.phone || "-"}</p>
                        </div>
                      </TableCell>
                      <TableCell className="text-right font-semibold text-primary">
                        ¥{Number(balance.balance).toFixed(2)}
                      </TableCell>
                      <TableCell className="text-right">¥{Number(balance.total_recharged).toFixed(2)}</TableCell>
                      <TableCell className="text-right text-green-600">¥{Number(balance.total_bonus).toFixed(2)}</TableCell>
                      <TableCell className="text-right text-orange-600">¥{Number(balance.total_consumed).toFixed(2)}</TableCell>
                      <TableCell className="text-muted-foreground">
                        {new Date(balance.created_at).toLocaleDateString()}
                      </TableCell>
                    </TableRow>
                  ))}
                  {filteredBalances.length === 0 && !loading && (
                    <TableRow>
                      <TableCell colSpan={6} className="text-center py-12 text-muted-foreground">
                        暂无会员余额数据
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </ScrollArea>
          </Card>
        </TabsContent>

        {/* 交易记录 */}
        <TabsContent value="transactions" className="space-y-4">
          <div className="flex justify-between items-center">
            <p className="text-sm text-muted-foreground">查看所有储值相关的交易记录</p>
            <Button variant="outline" onClick={fetchTransactions}>
              <RefreshCcw className="h-4 w-4 mr-2" />
              刷新
            </Button>
          </div>

          <Card>
            <ScrollArea className="h-[500px]">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>时间</TableHead>
                    <TableHead>会员</TableHead>
                    <TableHead>类型</TableHead>
                    <TableHead className="text-right">金额</TableHead>
                    <TableHead className="text-right">变动前</TableHead>
                    <TableHead className="text-right">变动后</TableHead>
                    <TableHead>备注</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {transactions.map(tx => {
                    const typeInfo = getTransactionTypeLabel(tx.type);
                    return (
                      <TableRow key={tx.id}>
                        <TableCell className="text-muted-foreground">
                          {new Date(tx.created_at).toLocaleString()}
                        </TableCell>
                        <TableCell>{tx.profile?.display_name || "未知"}</TableCell>
                        <TableCell>
                          <Badge variant={typeInfo.variant}>{typeInfo.text}</Badge>
                        </TableCell>
                        <TableCell className={`text-right font-medium ${tx.type === 'consume' ? 'text-orange-600' : 'text-green-600'}`}>
                          {tx.type === 'consume' ? '-' : '+'}¥{Math.abs(Number(tx.amount)).toFixed(2)}
                        </TableCell>
                        <TableCell className="text-right text-muted-foreground">
                          ¥{Number(tx.balance_before).toFixed(2)}
                        </TableCell>
                        <TableCell className="text-right font-medium">
                          ¥{Number(tx.balance_after).toFixed(2)}
                        </TableCell>
                        <TableCell className="text-muted-foreground max-w-[200px] truncate">
                          {tx.description || "-"}
                        </TableCell>
                      </TableRow>
                    );
                  })}
                  {transactions.length === 0 && !loading && (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center py-12 text-muted-foreground">
                        暂无交易记录
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </ScrollArea>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}