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, Zap, Clock, Trash2, Edit, Bot } from "lucide-react";

interface FlashSale {
  id: string;
  product_id: string;
  name: string;
  description: string | null;
  original_price: number;
  flash_price: number;
  stock_limit: number;
  sold_count: number;
  per_user_limit: number | null;
  start_time: string;
  end_time: string;
  status: string;
  type: string;
  created_by: string;
  ai_strategy: string | null;
  created_at: string;
  product?: { name: string; image_url: string | null };
}

interface Product {
  id: string;
  name: string;
  price: number;
  image_url: string | null;
}

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 typeConfig: Record<string, { label: string; icon: any }> = {
  flash_sale: { label: "秒杀", icon: Zap },
  time_discount: { label: "限时折扣", icon: Clock },
};

export function FlashSalesManager() {
  const [flashSales, setFlashSales] = useState<FlashSale[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<FlashSale | null>(null);
  
  const [formData, setFormData] = useState({
    product_id: "",
    name: "",
    description: "",
    flash_price: "",
    stock_limit: "100",
    per_user_limit: "1",
    start_time: "",
    end_time: "",
    type: "flash_sale",
  });

  useEffect(() => {
    fetchFlashSales();
    fetchProducts();
  }, []);

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

      if (error) throw error;
      setFlashSales(data || []);
    } catch (err) {
      console.error("Error fetching flash sales:", err);
      toast.error("获取秒杀活动失败");
    } finally {
      setIsLoading(false);
    }
  };

  const fetchProducts = async () => {
    try {
      const { data, error } = await supabase
        .from("products")
        .select("id, name, price, image_url")
        .eq("is_active", true)
        .order("name");

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

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

    const selectedProduct = products.find(p => p.id === formData.product_id);
    if (!selectedProduct) {
      toast.error("请选择商品");
      return;
    }

    try {
      const payload = {
        product_id: formData.product_id,
        name: formData.name,
        description: formData.description || null,
        original_price: selectedProduct.price,
        flash_price: parseFloat(formData.flash_price),
        stock_limit: parseInt(formData.stock_limit),
        per_user_limit: formData.per_user_limit ? parseInt(formData.per_user_limit) : null,
        start_time: new Date(formData.start_time).toISOString(),
        end_time: new Date(formData.end_time).toISOString(),
        type: formData.type,
        status: "draft",
      };

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

      setIsDialogOpen(false);
      resetForm();
      fetchFlashSales();
    } catch (err) {
      console.error("Error saving flash sale:", err);
      toast.error("保存失败");
    }
  };

  const handleEdit = (item: FlashSale) => {
    setEditingItem(item);
    setFormData({
      product_id: item.product_id,
      name: item.name,
      description: item.description || "",
      flash_price: item.flash_price.toString(),
      stock_limit: item.stock_limit.toString(),
      per_user_limit: item.per_user_limit?.toString() || "",
      start_time: format(new Date(item.start_time), "yyyy-MM-dd'T'HH:mm"),
      end_time: format(new Date(item.end_time), "yyyy-MM-dd'T'HH:mm"),
      type: item.type,
    });
    setIsDialogOpen(true);
  };

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

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

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

  const resetForm = () => {
    setEditingItem(null);
    setFormData({
      product_id: "",
      name: "",
      description: "",
      flash_price: "",
      stock_limit: "100",
      per_user_limit: "1",
      start_time: "",
      end_time: "",
      type: "flash_sale",
    });
  };

  const getProductName = (productId: string) => {
    const product = products.find(p => p.id === productId);
    return product?.name || "未知商品";
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="flex items-center gap-2">
          <Zap className="h-5 w-5 text-primary" />
          秒杀/限时折扣
        </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>
                <Select value={formData.type} onValueChange={(v) => setFormData({ ...formData, type: v })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="flash_sale">秒杀</SelectItem>
                    <SelectItem value="time_discount">限时折扣</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>选择商品 *</Label>
                <Select value={formData.product_id} onValueChange={(v) => setFormData({ ...formData, product_id: v })}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择商品" />
                  </SelectTrigger>
                  <SelectContent>
                    {products.map((product) => (
                      <SelectItem key={product.id} value={product.id}>
                        {product.name} (¥{product.price})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>活动名称 *</Label>
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="如：iPhone限时秒杀"
                />
              </div>
              <div className="space-y-2">
                <Label>活动描述</Label>
                <Input
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, 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={formData.flash_price}
                    onChange={(e) => setFormData({ ...formData, flash_price: e.target.value })}
                    placeholder="0.00"
                  />
                </div>
                <div className="space-y-2">
                  <Label>库存限制</Label>
                  <Input
                    type="number"
                    value={formData.stock_limit}
                    onChange={(e) => setFormData({ ...formData, stock_limit: e.target.value })}
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label>每人限购</Label>
                <Input
                  type="number"
                  value={formData.per_user_limit}
                  onChange={(e) => setFormData({ ...formData, per_user_limit: e.target.value })}
                  placeholder="不限制请留空"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>开始时间 *</Label>
                  <Input
                    type="datetime-local"
                    value={formData.start_time}
                    onChange={(e) => setFormData({ ...formData, start_time: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <Label>结束时间 *</Label>
                  <Input
                    type="datetime-local"
                    value={formData.end_time}
                    onChange={(e) => setFormData({ ...formData, end_time: 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>
              {flashSales.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                    暂无秒杀活动
                  </TableCell>
                </TableRow>
              ) : (
                flashSales.map((item) => {
                  const TypeIcon = typeConfig[item.type]?.icon || Zap;
                  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>
                        <div className="flex items-center gap-1">
                          <TypeIcon className="h-4 w-4" />
                          {typeConfig[item.type]?.label || item.type}
                        </div>
                      </TableCell>
                      <TableCell className="max-w-[120px] truncate">
                        {getProductName(item.product_id)}
                      </TableCell>
                      <TableCell>
                        <span className="text-muted-foreground line-through text-xs">¥{item.original_price}</span>
                        <span className="text-destructive font-bold ml-1">¥{item.flash_price}</span>
                      </TableCell>
                      <TableCell>
                        {item.sold_count}/{item.stock_limit}
                      </TableCell>
                      <TableCell className="text-xs">
                        {format(new Date(item.start_time), "MM/dd HH:mm", { locale: zhCN })}
                        <br />
                        {format(new Date(item.end_time), "MM/dd HH:mm", { 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>
  );
}
