import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Search, Edit, Trash2, Copy, TrendingUp } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { format } from "date-fns";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface Coupon {
  id: string;
  name: string;
  code: string;
  type: string;
  discount_value: number;
  min_purchase_amount: number;
  total_quantity: number;
  used_quantity: number;
  start_date: string;
  end_date: string;
  status: string;
  scope: string;
  description: string | null;
  created_at: string;
}

export function CouponManager() {
  const navigate = useNavigate();
  const [coupons, setCoupons] = useState<Coupon[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [couponToDelete, setCouponToDelete] = useState<string | null>(null);
  const { toast } = useToast();

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

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

      if (error) throw error;
      setCoupons(data || []);
    } catch (error) {
      console.error("Error fetching coupons:", error);
      toast({
        title: "错误",
        description: "获取优惠券列表失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleCreateCoupon = () => {
    navigate("/admin/coupons/new");
  };

  const handleEditCoupon = (id: string) => {
    navigate(`/admin/coupons/${id}`);
  };

  const handleDeleteCoupon = async () => {
    if (!couponToDelete) return;

    try {
      const { error } = await supabase
        .from("coupons")
        .delete()
        .eq("id", couponToDelete);

      if (error) throw error;

      toast({
        title: "成功",
        description: "优惠券已删除",
      });

      fetchCoupons();
    } catch (error) {
      console.error("Error deleting coupon:", error);
      toast({
        title: "错误",
        description: "删除优惠券失败",
        variant: "destructive",
      });
    } finally {
      setDeleteDialogOpen(false);
      setCouponToDelete(null);
    }
  };

  const handleCopyCode = (code: string) => {
    navigator.clipboard.writeText(code);
    toast({
      title: "已复制",
      description: `券码 ${code} 已复制到剪贴板`,
    });
  };

  const filteredCoupons = coupons.filter(
    (coupon) =>
      coupon.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      coupon.code.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const getStatusBadge = (status: string, startDate: string, endDate: string) => {
    const now = new Date();
    const start = new Date(startDate);
    const end = new Date(endDate);

    if (status === "inactive") {
      return <Badge variant="secondary">已禁用</Badge>;
    }

    if (now < start) {
      return <Badge variant="outline">未开始</Badge>;
    }

    if (now > end) {
      return <Badge variant="destructive">已过期</Badge>;
    }

    return <Badge variant="default">进行中</Badge>;
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("zh-CN", {
      style: "currency",
      currency: "CNY",
    }).format(amount);
  };

  const getUsageRate = (used: number, total: number) => {
    return total > 0 ? ((used / total) * 100).toFixed(1) : "0.0";
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Statistics Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总优惠券数</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{coupons.length}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">进行中</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {coupons.filter(c => {
                const now = new Date();
                return c.status === "active" && 
                  new Date(c.start_date) <= now && 
                  new Date(c.end_date) >= now;
              }).length}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已发放</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">
              {coupons.reduce((sum, c) => sum + c.used_quantity, 0)}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总库存</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-purple-600">
              {coupons.reduce((sum, c) => sum + c.total_quantity, 0)}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Coupon Management Card */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>折扣券管理</CardTitle>
              <CardDescription>创建和管理优惠券活动</CardDescription>
            </div>
            <Button onClick={handleCreateCoupon} className="flex items-center gap-2">
              <Plus className="h-4 w-4" />
              创建优惠券
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <div className="mb-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="搜索优惠券名称或券码..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>券名称</TableHead>
                <TableHead>券码</TableHead>
                <TableHead>类型</TableHead>
                <TableHead>优惠</TableHead>
                <TableHead>使用条件</TableHead>
                <TableHead>库存</TableHead>
                <TableHead>有效期</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredCoupons.map((coupon) => (
                <TableRow key={coupon.id}>
                  <TableCell className="font-medium">{coupon.name}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <code className="px-2 py-1 bg-muted rounded text-sm">
                        {coupon.code}
                      </code>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleCopyCode(coupon.code)}
                      >
                        <Copy className="h-3 w-3" />
                      </Button>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {coupon.type === "amount" ? "金额券" : "折扣券"}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {coupon.type === "amount"
                      ? formatCurrency(coupon.discount_value)
                      : `${coupon.discount_value}%`}
                  </TableCell>
                  <TableCell>
                    {coupon.min_purchase_amount > 0
                      ? `满${formatCurrency(coupon.min_purchase_amount)}`
                      : "无门槛"}
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-col">
                      <span className="text-sm">
                        {coupon.used_quantity}/{coupon.total_quantity}
                      </span>
                      <span className="text-xs text-muted-foreground">
                        {getUsageRate(coupon.used_quantity, coupon.total_quantity)}%
                      </span>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div>{format(new Date(coupon.start_date), "yyyy-MM-dd")}</div>
                      <div className="text-muted-foreground">
                        至 {format(new Date(coupon.end_date), "yyyy-MM-dd")}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    {getStatusBadge(coupon.status, coupon.start_date, coupon.end_date)}
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEditCoupon(coupon.id)}
                      >
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          setCouponToDelete(coupon.id);
                          setDeleteDialogOpen(true);
                        }}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>

          {filteredCoupons.length === 0 && (
            <div className="text-center py-8 text-muted-foreground">
              {searchTerm ? "没有找到匹配的优惠券" : "暂无优惠券，点击上方按钮创建"}
            </div>
          )}
        </CardContent>
      </Card>

      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除这张优惠券吗？此操作无法撤销，已领取的用户将无法使用该券。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={handleDeleteCoupon}>
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}