import { useState, useEffect, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import {
  Clock,
  CheckCircle2,
  XCircle,
  Megaphone,
  Headphones,
  Zap,
  Package,
  Users,
  ArrowRight,
  RefreshCw,
  Bot,
  AlertTriangle,
} from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";

// 统一审批项类型
export interface ApprovalItem {
  id: string;
  type: "marketing" | "aftersales" | "flash_sale" | "group_buy" | "product";
  title: string;
  description: string;
  agent: string;
  priority: "low" | "medium" | "high" | "urgent";
  amount?: number;
  createdAt: Date;
  metadata?: Record<string, any>;
}

interface UnifiedApprovalCenterProps {
  onNavigate?: (tab: string) => void;
  height?: string;
  compact?: boolean;
}

const typeConfig = {
  marketing: {
    label: "营销活动",
    icon: Megaphone,
    color: "text-orange-500",
    bgColor: "bg-orange-500/10",
    agent: "小营",
    tab: "marketing",
  },
  aftersales: {
    label: "售后申请",
    icon: Headphones,
    color: "text-blue-500",
    bgColor: "bg-blue-500/10",
    agent: "小服",
    tab: "aftersales",
  },
  flash_sale: {
    label: "限时抢购",
    icon: Zap,
    color: "text-yellow-500",
    bgColor: "bg-yellow-500/10",
    agent: "小营",
    tab: "marketing",
  },
  group_buy: {
    label: "拼团活动",
    icon: Users,
    color: "text-purple-500",
    bgColor: "bg-purple-500/10",
    agent: "小营",
    tab: "marketing",
  },
  product: {
    label: "商品审核",
    icon: Package,
    color: "text-green-500",
    bgColor: "bg-green-500/10",
    agent: "小品",
    tab: "products",
  },
};

const priorityConfig = {
  low: { label: "普通", color: "bg-muted text-muted-foreground" },
  medium: { label: "重要", color: "bg-blue-500/20 text-blue-600" },
  high: { label: "紧急", color: "bg-amber-500/20 text-amber-600" },
  urgent: { label: "加急", color: "bg-destructive/20 text-destructive" },
};

export function UnifiedApprovalCenter({
  onNavigate,
  height = "400px",
  compact = false,
}: UnifiedApprovalCenterProps) {
  const [approvals, setApprovals] = useState<ApprovalItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<string>("all");
  const [processingId, setProcessingId] = useState<string | null>(null);

  // 从各表获取待审批数据
  const fetchApprovals = useCallback(async () => {
    setLoading(true);
    try {
      const items: ApprovalItem[] = [];

      // 1. 获取待审批的营销活动
      const { data: campaigns } = await supabase
        .from("marketing_campaigns")
        .select("*")
        .eq("status", "pending")
        .order("created_at", { ascending: false })
        .limit(10);

      campaigns?.forEach((c) => {
        items.push({
          id: c.id,
          type: "marketing",
          title: c.name,
          description: c.description || "营销活动待审批",
          agent: "小营",
          priority: "medium",
          createdAt: new Date(c.created_at),
          metadata: { config: c.config, aiStrategy: c.ai_strategy },
        });
      });

      // 2. 获取待处理的售后申请
      const { data: afterSales } = await supabase
        .from("after_sales_requests")
        .select(
          `
          *,
          products:product_id (name, price),
          orders:order_id (order_number)
        `
        )
        .eq("status", "pending")
        .order("created_at", { ascending: false })
        .limit(10);

      afterSales?.forEach((a) => {
        const priority =
          a.refund_amount && a.refund_amount > 500 ? "high" : "medium";
        items.push({
          id: a.id,
          type: "aftersales",
          title: `${a.type === "refund" ? "退款" : a.type === "exchange" ? "换货" : "退货"}申请`,
          description: `订单 ${(a.orders as any)?.order_number || "未知"} - ${(a.products as any)?.name || "商品"}`,
          agent: "小服",
          priority,
          amount: a.refund_amount || undefined,
          createdAt: new Date(a.created_at),
          metadata: { reason: a.reason, description: a.description },
        });
      });

      // 3. 获取待审批的限时抢购
      const { data: flashSales } = await supabase
        .from("flash_sales")
        .select(
          `
          *,
          products:product_id (name)
        `
        )
        .eq("status", "draft")
        .order("created_at", { ascending: false })
        .limit(5);

      flashSales?.forEach((f) => {
        items.push({
          id: f.id,
          type: "flash_sale",
          title: f.name,
          description: `商品: ${(f.products as any)?.name || "未知"} - 抢购价 ¥${f.flash_price}`,
          agent: "小营",
          priority: "medium",
          amount: f.flash_price,
          createdAt: new Date(f.created_at),
          metadata: {
            originalPrice: f.original_price,
            stockLimit: f.stock_limit,
          },
        });
      });

      // 4. 获取待审批的拼团活动
      const { data: groupBuys } = await supabase
        .from("group_buy_activities")
        .select(
          `
          *,
          products:product_id (name)
        `
        )
        .eq("status", "draft")
        .order("created_at", { ascending: false })
        .limit(5);

      groupBuys?.forEach((g) => {
        items.push({
          id: g.id,
          type: "group_buy",
          title: g.name,
          description: `商品: ${(g.products as any)?.name || "未知"} - 拼团价 ¥${g.group_price}`,
          agent: "小营",
          priority: "low",
          amount: g.group_price,
          createdAt: new Date(g.created_at),
          metadata: {
            minGroupSize: g.min_group_size,
            maxGroupSize: g.max_group_size,
          },
        });
      });

      // 按时间排序，紧急的放前面
      items.sort((a, b) => {
        const priorityOrder = { urgent: 0, high: 1, medium: 2, low: 3 };
        if (priorityOrder[a.priority] !== priorityOrder[b.priority]) {
          return priorityOrder[a.priority] - priorityOrder[b.priority];
        }
        return b.createdAt.getTime() - a.createdAt.getTime();
      });

      setApprovals(items);
    } catch (error) {
      console.error("获取审批数据失败:", error);
      toast.error("获取审批数据失败");
    } finally {
      setLoading(false);
    }
  }, []);

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

  // 处理审批操作
  const handleApprove = async (item: ApprovalItem) => {
    setProcessingId(item.id);
    try {
      let updateResult;

      switch (item.type) {
        case "marketing":
          updateResult = await supabase
            .from("marketing_campaigns")
            .update({ status: "active", reviewed_at: new Date().toISOString() })
            .eq("id", item.id);
          break;

        case "aftersales":
          updateResult = await supabase
            .from("after_sales_requests")
            .update({
              status: "approved",
              processed_at: new Date().toISOString(),
            })
            .eq("id", item.id);
          break;

        case "flash_sale":
          updateResult = await supabase
            .from("flash_sales")
            .update({ status: "active" })
            .eq("id", item.id);
          break;

        case "group_buy":
          updateResult = await supabase
            .from("group_buy_activities")
            .update({ status: "active" })
            .eq("id", item.id);
          break;
      }

      if (updateResult?.error) throw updateResult.error;

      toast.success(`已批准: ${item.title}`);
      setApprovals((prev) => prev.filter((a) => a.id !== item.id));
    } catch (error) {
      console.error("批准失败:", error);
      toast.error("操作失败，请重试");
    } finally {
      setProcessingId(null);
    }
  };

  const handleReject = async (item: ApprovalItem) => {
    setProcessingId(item.id);
    try {
      let updateResult;

      switch (item.type) {
        case "marketing":
          updateResult = await supabase
            .from("marketing_campaigns")
            .update({
              status: "rejected",
              reviewed_at: new Date().toISOString(),
            })
            .eq("id", item.id);
          break;

        case "aftersales":
          updateResult = await supabase
            .from("after_sales_requests")
            .update({
              status: "rejected",
              processed_at: new Date().toISOString(),
            })
            .eq("id", item.id);
          break;

        case "flash_sale":
          updateResult = await supabase
            .from("flash_sales")
            .update({ status: "cancelled" })
            .eq("id", item.id);
          break;

        case "group_buy":
          updateResult = await supabase
            .from("group_buy_activities")
            .update({ status: "cancelled" })
            .eq("id", item.id);
          break;
      }

      if (updateResult?.error) throw updateResult.error;

      toast.info(`已拒绝: ${item.title}`);
      setApprovals((prev) => prev.filter((a) => a.id !== item.id));
    } catch (error) {
      console.error("拒绝失败:", error);
      toast.error("操作失败，请重试");
    } finally {
      setProcessingId(null);
    }
  };

  const handleViewDetail = (item: ApprovalItem) => {
    const config = typeConfig[item.type];
    if (onNavigate && config.tab) {
      onNavigate(config.tab);
    }
  };

  // 按类型筛选
  const filteredApprovals =
    activeTab === "all"
      ? approvals
      : approvals.filter((a) => a.type === activeTab);

  // 统计各类型数量
  const typeCounts = approvals.reduce(
    (acc, item) => {
      acc[item.type] = (acc[item.type] || 0) + 1;
      return acc;
    },
    {} as Record<string, number>
  );

  const renderApprovalItem = (item: ApprovalItem) => {
    const config = typeConfig[item.type];
    const priority = priorityConfig[item.priority];
    const Icon = config.icon;
    const isProcessing = processingId === item.id;

    return (
      <div
        key={item.id}
        className="p-4 rounded-lg border bg-card hover:shadow-md transition-all"
      >
        <div className="flex items-start gap-3">
          <div
            className={`h-10 w-10 rounded-full ${config.bgColor} flex items-center justify-center flex-shrink-0`}
          >
            <Icon className={`h-5 w-5 ${config.color}`} />
          </div>

          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1 flex-wrap">
              <h4 className="font-medium text-sm truncate">{item.title}</h4>
              <Badge className={`text-xs ${priority.color}`}>
                {priority.label}
              </Badge>
              <Badge variant="outline" className="text-xs">
                <Bot className="h-3 w-3 mr-1" />
                {config.agent}
              </Badge>
            </div>

            <p className="text-xs text-muted-foreground mb-2 line-clamp-2">
              {item.description}
            </p>

            {item.amount !== undefined && (
              <p className="text-xs font-medium text-primary mb-2">
                金额: ¥{item.amount.toLocaleString()}
              </p>
            )}

            <div className="flex items-center justify-between">
              <span className="text-xs text-muted-foreground">
                {formatDistanceToNow(item.createdAt, {
                  addSuffix: true,
                  locale: zhCN,
                })}
              </span>

              <div className="flex items-center gap-2">
                <Button
                  size="sm"
                  variant="ghost"
                  className="h-7 text-xs"
                  onClick={() => handleViewDetail(item)}
                  disabled={isProcessing}
                >
                  详情
                  <ArrowRight className="h-3 w-3 ml-1" />
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  className="h-7 text-xs text-destructive hover:text-destructive"
                  onClick={() => handleReject(item)}
                  disabled={isProcessing}
                >
                  <XCircle className="h-3 w-3 mr-1" />
                  拒绝
                </Button>
                <Button
                  size="sm"
                  variant="default"
                  className="h-7 text-xs"
                  onClick={() => handleApprove(item)}
                  disabled={isProcessing}
                >
                  {isProcessing ? (
                    <RefreshCw className="h-3 w-3 mr-1 animate-spin" />
                  ) : (
                    <CheckCircle2 className="h-3 w-3 mr-1" />
                  )}
                  批准
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  const urgentCount = approvals.filter(
    (a) => a.priority === "urgent" || a.priority === "high"
  ).length;

  return (
    <Card className="h-full">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Clock className="h-5 w-5 text-amber-500" />
            <CardTitle className="text-base">统一审批中心</CardTitle>
          </div>
          <div className="flex items-center gap-2">
            {urgentCount > 0 && (
              <Badge variant="destructive" className="text-xs">
                <AlertTriangle className="h-3 w-3 mr-1" />
                {urgentCount} 紧急
              </Badge>
            )}
            <Badge variant="secondary" className="text-xs">
              {approvals.length} 待处理
            </Badge>
            <Button
              variant="ghost"
              size="sm"
              onClick={fetchApprovals}
              disabled={loading}
            >
              <RefreshCw
                className={`h-4 w-4 ${loading ? "animate-spin" : ""}`}
              />
            </Button>
          </div>
        </div>
      </CardHeader>

      {!compact && (
        <div className="px-4 pb-2">
          <Tabs value={activeTab} onValueChange={setActiveTab}>
            <TabsList className="h-8">
              <TabsTrigger value="all" className="text-xs h-7">
                全部 ({approvals.length})
              </TabsTrigger>
              {Object.entries(typeConfig).map(([key, config]) => {
                const count = typeCounts[key] || 0;
                if (count === 0) return null;
                return (
                  <TabsTrigger key={key} value={key} className="text-xs h-7">
                    {config.label} ({count})
                  </TabsTrigger>
                );
              })}
            </TabsList>
          </Tabs>
        </div>
      )}

      <ScrollArea style={{ height }}>
        <div className="p-4 pt-2 space-y-3">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <RefreshCw className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : filteredApprovals.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <CheckCircle2 className="h-12 w-12 mx-auto mb-3 opacity-20" />
              <p>暂无待审批事项</p>
              <p className="text-sm mt-1">各部门的审批请求将在这里汇总</p>
            </div>
          ) : (
            filteredApprovals.map(renderApprovalItem)
          )}
        </div>
      </ScrollArea>
    </Card>
  );
}
