/**
 * 充值套餐管理 - 静态组件
 * 提供完整的 CRUD 功能用于管理充值套餐
 */

import { useState, useEffect } from "react";
import { Card, CardContent, 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 { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Plus, Edit, Trash2, Gift } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

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

export function MembershipPlansView() {
  const [plans, setPlans] = useState<RechargePlan[]>([]);
  const [loading, setLoading] = useState(true);
  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
  });

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

  const fetchPlans = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from("recharge_plans")
        .select("*")
        .order("display_order", { ascending: true });
      
      if (error) throw error;
      setPlans(data || []);
    } catch (error) {
      console.error("获取套餐失败:", error);
      toast.error("获取充值套餐失败");
    } finally {
      setLoading(false);
    }
  };

  const handleSavePlan = async () => {
    if (!planForm.name || planForm.recharge_amount <= 0) {
      toast.error("请填写套餐名称和充值金额");
      return;
    }

    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 openNewPlanDialog = () => {
    setEditingPlan(null);
    resetPlanForm();
    setPlanDialogOpen(true);
  };

  if (loading) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {[1, 2, 3].map((i) => (
          <Card key={i} className="animate-pulse">
            <CardHeader>
              <div className="h-5 bg-muted rounded w-24" />
            </CardHeader>
            <CardContent>
              <div className="h-8 bg-muted rounded w-20 mb-2" />
              <div className="h-4 bg-muted rounded w-32" />
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* 头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold">充值套餐管理</h3>
          <p className="text-sm text-muted-foreground">管理会员储值套餐和优惠</p>
        </div>
        <Dialog open={planDialogOpen} onOpenChange={setPlanDialogOpen}>
          <DialogTrigger asChild>
            <Button onClick={openNewPlanDialog}>
              <Plus className="h-4 w-4 mr-2" />
              添加套餐
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{editingPlan ? "编辑套餐" : "添加套餐"}</DialogTitle>
              <DialogDescription>
                {editingPlan ? "修改储值套餐信息" : "创建新的储值套餐"}
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label>套餐名称</Label>
                <Input
                  value={planForm.name}
                  onChange={(e) => setPlanForm({ ...planForm, name: e.target.value })}
                  placeholder="如：黄金会员"
                />
              </div>
              <div className="space-y-2">
                <Label>描述</Label>
                <Input
                  value={planForm.description}
                  onChange={(e) => setPlanForm({ ...planForm, 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({ ...planForm, recharge_amount: Number(e.target.value) })}
                  />
                </div>
                <div className="space-y-2">
                  <Label>赠送金额 (¥)</Label>
                  <Input
                    type="number"
                    value={planForm.bonus_amount}
                    onChange={(e) => setPlanForm({ ...planForm, 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({ ...planForm, display_order: Number(e.target.value) })}
                  />
                </div>
                <div className="flex items-center gap-2 pt-6">
                  <Switch
                    checked={planForm.is_active}
                    onCheckedChange={(checked) => setPlanForm({ ...planForm, is_active: checked })}
                  />
                  <Label>启用</Label>
                </div>
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setPlanDialogOpen(false)}>
                取消
              </Button>
              <Button onClick={handleSavePlan}>
                保存
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* 套餐列表 */}
      {plans.length === 0 ? (
        <Card>
          <CardContent className="p-8 text-center">
            <Gift className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">暂无充值套餐</p>
            <Button className="mt-4" onClick={openNewPlanDialog}>
              创建第一个套餐
            </Button>
          </CardContent>
        </Card>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {plans.map((plan) => (
            <Card key={plan.id} className={!plan.is_active ? 'opacity-60' : ''}>
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-base">{plan.name}</CardTitle>
                  <div className="flex items-center gap-1">
                    {!plan.is_active && (
                      <Badge variant="secondary" className="text-xs">已停用</Badge>
                    )}
                    {plan.bonus_amount > 0 && (
                      <Badge variant="default" className="text-xs">
                        送¥{plan.bonus_amount}
                      </Badge>
                    )}
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div>
                    <p className="text-2xl font-bold">¥{plan.recharge_amount}</p>
                    {plan.bonus_amount > 0 && (
                      <p className="text-sm text-muted-foreground">
                        实得 ¥{plan.recharge_amount + plan.bonus_amount}
                      </p>
                    )}
                  </div>
                  {plan.description && (
                    <p className="text-sm text-muted-foreground">{plan.description}</p>
                  )}
                  <div className="flex gap-2 pt-2">
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleEditPlan(plan)}
                    >
                      <Edit className="h-3 w-3 mr-1" />
                      编辑
                    </Button>
                    <Button
                      size="sm"
                      variant="destructive"
                      onClick={() => handleDeletePlan(plan.id)}
                    >
                      <Trash2 className="h-3 w-3 mr-1" />
                      删除
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
