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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { ScrollArea } from "@/components/ui/scroll-area";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { format } from "date-fns";
import { zhCN } from "date-fns/locale";
import { Plus, Gift, Trash2, Edit, Bot, Ticket, Coins } from "lucide-react";

interface PaymentGift {
  id: string;
  name: string;
  description: string | null;
  min_payment_amount: number;
  gift_type: string;
  gift_value: any;
  probability: number;
  total_quantity: number | null;
  used_quantity: number;
  start_date: string;
  end_date: string;
  status: string;
  created_by: string;
  ai_strategy: string | null;
  created_at: string;
}

interface Coupon {
  id: string;
  name: string;
  code: string;
}

const statusConfig: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
  draft: { label: "草稿", variant: "secondary" },
  active: { label: "进行中", variant: "default" },
  paused: { label: "已暂停", variant: "outline" },
  ended: { label: "已结束", variant: "destructive" },
};

const giftTypeConfig: Record<string, { label: string; icon: any }> = {
  coupon: { label: "优惠券", icon: Ticket },
  points: { label: "积分", icon: Coins },
  random_coupon: { label: "随机优惠券", icon: Gift },
};

export function PaymentGiftsManager() {
  const [paymentGifts, setPaymentGifts] = useState<PaymentGift[]>([]);
  const [coupons, setCoupons] = useState<Coupon[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<PaymentGift | null>(null);
  
  const [formData, setFormData] = useState({
    name: "",
    description: "",
    min_payment_amount: "0",
    gift_type: "coupon",
    coupon_id: "",
    points_amount: "",
    probability: "100",
    total_quantity: "",
    start_date: "",
    end_date: "",
  });

  useEffect(() => {
    fetchPaymentGifts();
    fetchCoupons();
  }, []);

  const fetchPaymentGifts = async () => {
    try {
      const { data, error } = await supabase
        .from("payment_gifts")
        .select("*")
        .order("created_at", { ascending: false });

      if (error) throw error;
      setPaymentGifts(data || []);
    } catch (err) {
      console.error("Error fetching payment gifts:", err);
      toast.error("获取支付有礼活动失败");
    } finally {
      setIsLoading(false);
    }
  };

  const fetchCoupons = async () => {
    try {
      const { data, error } = await supabase
        .from("coupons")
        .select("id, name, code")
        .eq("status", "active")
        .order("name");

      if (error) throw error;
      setCoupons(data || []);
    } catch (err) {
      console.error("Error fetching coupons:", err);
    }
  };

  const handleSubmit = async () => {
    if (!formData.name || !formData.start_date || !formData.end_date) {
      toast.error("请填写必填字段");
      return;
    }

    let giftValue: Record<string, any> = {};
    if (formData.gift_type === "coupon" && formData.coupon_id) {
      giftValue = { coupon_id: formData.coupon_id };
    } else if (formData.gift_type === "points" && formData.points_amount) {
      giftValue = { points: parseInt(formData.points_amount) };
    }

    try {
      const payload = {
        name: formData.name,
        description: formData.description || null,
        min_payment_amount: parseFloat(formData.min_payment_amount) || 0,
        gift_type: formData.gift_type,
        gift_value: giftValue,
        probability: parseInt(formData.probability) || 100,
        total_quantity: formData.total_quantity ? parseInt(formData.total_quantity) : null,
        start_date: new Date(formData.start_date).toISOString(),
        end_date: new Date(formData.end_date).toISOString(),
        status: "draft",
      };

      if (editingItem) {
        const { error } = await supabase
          .from("payment_gifts")
          .update(payload)
          .eq("id", editingItem.id);
        if (error) throw error;
        toast.success("更新成功");
      } else {
        const { error } = await supabase
          .from("payment_gifts")
          .insert(payload);
        if (error) throw error;
        toast.success("创建成功");
      }

      setIsDialogOpen(false);
      resetForm();
      fetchPaymentGifts();
    } catch (err) {
      console.error("Error saving payment gift:", err);
      toast.error("保存失败");
    }
  };

  const handleEdit = (item: PaymentGift) => {
    setEditingItem(item);
    setFormData({
      name: item.name,
      description: item.description || "",
      min_payment_amount: item.min_payment_amount.toString(),
      gift_type: item.gift_type,
      coupon_id: item.gift_value?.coupon_id || "",
      points_amount: item.gift_value?.points?.toString() || "",
      probability: item.probability.toString(),
      total_quantity: item.total_quantity?.toString() || "",
      start_date: format(new Date(item.start_date), "yyyy-MM-dd'T'HH:mm"),
      end_date: format(new Date(item.end_date), "yyyy-MM-dd'T'HH:mm"),
    });
    setIsDialogOpen(true);
  };

  const handleDelete = async (id: string) => {
    if (!confirm("确定要删除此活动吗？")) return;

    try {
      const { error } = await supabase
        .from("payment_gifts")
        .delete()
        .eq("id", id);
      if (error) throw error;
      toast.success("删除成功");
      fetchPaymentGifts();
    } catch (err) {
      console.error("Error deleting payment gift:", err);
      toast.error("删除失败");
    }
  };

  const handleStatusChange = async (id: string, newStatus: string) => {
    try {
      const { error } = await supabase
        .from("payment_gifts")
        .update({ status: newStatus })
        .eq("id", id);
      if (error) throw error;
      toast.success("状态更新成功");
      fetchPaymentGifts();
    } catch (err) {
      console.error("Error updating status:", err);
      toast.error("状态更新失败");
    }
  };

  const resetForm = () => {
    setEditingItem(null);
    setFormData({
      name: "",
      description: "",
      min_payment_amount: "0",
      gift_type: "coupon",
      coupon_id: "",
      points_amount: "",
      probability: "100",
      total_quantity: "",
      start_date: "",
      end_date: "",
    });
  };

  const getGiftDescription = (item: PaymentGift) => {
    if (item.gift_type === "coupon") {
      const coupon = coupons.find(c => c.id === item.gift_value?.coupon_id);
      return coupon ? coupon.name : "优惠券";
    } else if (item.gift_type === "points") {
      return `${item.gift_value?.points || 0} 积分`;
    }
    return "随机礼品";
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="flex items-center gap-2">
          <Gift className="h-5 w-5 text-chart-2" />
          支付有礼
        </CardTitle>
        <Dialog open={isDialogOpen} onOpenChange={(open) => {
          setIsDialogOpen(open);
          if (!open) resetForm();
        }}>
          <DialogTrigger asChild>
            <Button size="sm">
              <Plus className="h-4 w-4 mr-1" />
              创建活动
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg">
            <DialogHeader>
              <DialogTitle>{editingItem ? "编辑活动" : "创建支付有礼活动"}</DialogTitle>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label>活动名称 *</Label>
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="如：满100送优惠券"
                />
              </div>
              <div className="space-y-2">
                <Label>活动描述</Label>
                <Input
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="活动详情描述"
                />
              </div>
              <div className="space-y-2">
                <Label>最低消费金额</Label>
                <Input
                  type="number"
                  value={formData.min_payment_amount}
                  onChange={(e) => setFormData({ ...formData, min_payment_amount: e.target.value })}
                  placeholder="0 表示不限制"
                />
              </div>
              <div className="space-y-2">
                <Label>礼品类型</Label>
                <Select value={formData.gift_type} onValueChange={(v) => setFormData({ ...formData, gift_type: v })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="coupon">优惠券</SelectItem>
                    <SelectItem value="points">积分</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {formData.gift_type === "coupon" && (
                <div className="space-y-2">
                  <Label>选择优惠券</Label>
                  <Select value={formData.coupon_id} onValueChange={(v) => setFormData({ ...formData, coupon_id: v })}>
                    <SelectTrigger>
                      <SelectValue placeholder="选择优惠券" />
                    </SelectTrigger>
                    <SelectContent>
                      {coupons.map((coupon) => (
                        <SelectItem key={coupon.id} value={coupon.id}>
                          {coupon.name} ({coupon.code})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}
              {formData.gift_type === "points" && (
                <div className="space-y-2">
                  <Label>赠送积分</Label>
                  <Input
                    type="number"
                    value={formData.points_amount}
                    onChange={(e) => setFormData({ ...formData, points_amount: e.target.value })}
                    placeholder="积分数量"
                  />
                </div>
              )}
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>中奖概率 (%)</Label>
                  <Input
                    type="number"
                    value={formData.probability}
                    onChange={(e) => setFormData({ ...formData, probability: e.target.value })}
                    min="1"
                    max="100"
                  />
                </div>
                <div className="space-y-2">
                  <Label>总数量</Label>
                  <Input
                    type="number"
                    value={formData.total_quantity}
                    onChange={(e) => setFormData({ ...formData, total_quantity: e.target.value })}
                    placeholder="不限制请留空"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>开始时间 *</Label>
                  <Input
                    type="datetime-local"
                    value={formData.start_date}
                    onChange={(e) => setFormData({ ...formData, start_date: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <Label>结束时间 *</Label>
                  <Input
                    type="datetime-local"
                    value={formData.end_date}
                    onChange={(e) => setFormData({ ...formData, end_date: e.target.value })}
                  />
                </div>
              </div>
              <Button onClick={handleSubmit} className="w-full">
                {editingItem ? "保存修改" : "创建活动"}
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </CardHeader>
      <CardContent>
        <ScrollArea className="h-[400px]">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>活动名称</TableHead>
                <TableHead>最低消费</TableHead>
                <TableHead>礼品</TableHead>
                <TableHead>概率</TableHead>
                <TableHead>使用/总量</TableHead>
                <TableHead>时间</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {paymentGifts.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                    暂无支付有礼活动
                  </TableCell>
                </TableRow>
              ) : (
                paymentGifts.map((item) => {
                  const TypeIcon = giftTypeConfig[item.gift_type]?.icon || Gift;
                  return (
                    <TableRow key={item.id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {item.created_by === "ai" && (
                            <Bot className="h-4 w-4 text-chart-2" />
                          )}
                          <span className="font-medium">{item.name}</span>
                        </div>
                      </TableCell>
                      <TableCell>¥{item.min_payment_amount}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          <TypeIcon className="h-4 w-4" />
                          {getGiftDescription(item)}
                        </div>
                      </TableCell>
                      <TableCell>{item.probability}%</TableCell>
                      <TableCell>
                        {item.used_quantity}/{item.total_quantity || "∞"}
                      </TableCell>
                      <TableCell className="text-xs">
                        {format(new Date(item.start_date), "MM/dd", { locale: zhCN })} -
                        {format(new Date(item.end_date), "MM/dd", { locale: zhCN })}
                      </TableCell>
                      <TableCell>
                        <Select value={item.status} onValueChange={(v) => handleStatusChange(item.id, v)}>
                          <SelectTrigger className="w-[90px] h-7">
                            <Badge variant={statusConfig[item.status]?.variant || "secondary"}>
                              {statusConfig[item.status]?.label || item.status}
                            </Badge>
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="draft">草稿</SelectItem>
                            <SelectItem value="active">进行中</SelectItem>
                            <SelectItem value="paused">暂停</SelectItem>
                            <SelectItem value="ended">结束</SelectItem>
                          </SelectContent>
                        </Select>
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-1">
                          <Button variant="ghost" size="icon" onClick={() => handleEdit(item)}>
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="icon" onClick={() => handleDelete(item.id)}>
                            <Trash2 className="h-4 w-4 text-destructive" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}
