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

interface GroupBuyActivity {
  id: string;
  product_id: string;
  name: string;
  description: string | null;
  original_price: number;
  group_price: number;
  min_group_size: number;
  max_group_size: number;
  duration_hours: number;
  stock_limit: number | null;
  sold_count: number;
  start_date: string;
  end_date: string;
  status: string;
  created_by: string;
  ai_strategy: string | null;
  created_at: string;
}

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" },
};

export function GroupBuyManager() {
  const [activities, setActivities] = useState<GroupBuyActivity[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<GroupBuyActivity | null>(null);
  
  const [formData, setFormData] = useState({
    product_id: "",
    name: "",
    description: "",
    group_price: "",
    min_group_size: "2",
    max_group_size: "10",
    duration_hours: "24",
    stock_limit: "",
    start_date: "",
    end_date: "",
  });

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

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

      if (error) throw error;
      setActivities(data || []);
    } catch (err) {
      console.error("Error fetching group buy activities:", 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.group_price || !formData.start_date || !formData.end_date) {
      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,
        group_price: parseFloat(formData.group_price),
        min_group_size: parseInt(formData.min_group_size),
        max_group_size: parseInt(formData.max_group_size),
        duration_hours: parseInt(formData.duration_hours),
        stock_limit: formData.stock_limit ? parseInt(formData.stock_limit) : 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("group_buy_activities")
          .update(payload)
          .eq("id", editingItem.id);
        if (error) throw error;
        toast.success("更新成功");
      } else {
        const { error } = await supabase
          .from("group_buy_activities")
          .insert(payload);
        if (error) throw error;
        toast.success("创建成功");
      }

      setIsDialogOpen(false);
      resetForm();
      fetchActivities();
    } catch (err) {
      console.error("Error saving group buy activity:", err);
      toast.error("保存失败");
    }
  };

  const handleEdit = (item: GroupBuyActivity) => {
    setEditingItem(item);
    setFormData({
      product_id: item.product_id,
      name: item.name,
      description: item.description || "",
      group_price: item.group_price.toString(),
      min_group_size: item.min_group_size.toString(),
      max_group_size: item.max_group_size.toString(),
      duration_hours: item.duration_hours.toString(),
      stock_limit: item.stock_limit?.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("group_buy_activities")
        .delete()
        .eq("id", id);
      if (error) throw error;
      toast.success("删除成功");
      fetchActivities();
    } catch (err) {
      console.error("Error deleting group buy activity:", err);
      toast.error("删除失败");
    }
  };

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

  const resetForm = () => {
    setEditingItem(null);
    setFormData({
      product_id: "",
      name: "",
      description: "",
      group_price: "",
      min_group_size: "2",
      max_group_size: "10",
      duration_hours: "24",
      stock_limit: "",
      start_date: "",
      end_date: "",
    });
  };

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

  const calculateDiscount = (original: number, group: number) => {
    return Math.round((1 - group / original) * 100);
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle className="flex items-center gap-2">
          <Users className="h-5 w-5 text-chart-5" />
          多人拼团
        </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.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="如：3人成团享优惠"
                />
              </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.group_price}
                  onChange={(e) => setFormData({ ...formData, group_price: e.target.value })}
                  placeholder="0.00"
                />
              </div>
              <div className="grid grid-cols-3 gap-4">
                <div className="space-y-2">
                  <Label>最少人数</Label>
                  <Input
                    type="number"
                    value={formData.min_group_size}
                    onChange={(e) => setFormData({ ...formData, min_group_size: e.target.value })}
                    min="2"
                  />
                </div>
                <div className="space-y-2">
                  <Label>最多人数</Label>
                  <Input
                    type="number"
                    value={formData.max_group_size}
                    onChange={(e) => setFormData({ ...formData, max_group_size: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <Label>成团时限(时)</Label>
                  <Input
                    type="number"
                    value={formData.duration_hours}
                    onChange={(e) => setFormData({ ...formData, duration_hours: e.target.value })}
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label>库存限制</Label>
                <Input
                  type="number"
                  value={formData.stock_limit}
                  onChange={(e) => setFormData({ ...formData, stock_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_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>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {activities.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                    暂无拼团活动
                  </TableCell>
                </TableRow>
              ) : (
                activities.map((item) => (
                  <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 className="max-w-[100px] truncate">
                      {getProductName(item.product_id)}
                    </TableCell>
                    <TableCell>
                      <div>
                        <span className="text-muted-foreground line-through text-xs">¥{item.original_price}</span>
                        <span className="text-chart-5 font-bold ml-1">¥{item.group_price}</span>
                      </div>
                      <Badge variant="outline" className="text-xs">
                        省{calculateDiscount(item.original_price, item.group_price)}%
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {item.min_group_size}-{item.max_group_size}人
                    </TableCell>
                    <TableCell>{item.duration_hours}小时</TableCell>
                    <TableCell>
                      {item.sold_count}{item.stock_limit ? `/${item.stock_limit}` : ""}
                    </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>
  );
}
