/**
 * GenUI 审批列表组件
 * 支持 Agent 动态控制分组和优先级排序
 */

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 {
  Clock,
  CheckCircle2,
  XCircle,
  Megaphone,
  Headphones,
  Zap,
  Package,
  Users,
  ArrowRight,
  RefreshCw,
  Bot,
  AlertTriangle,
} from "lucide-react";
import type { RenderContext } from '../types';

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

// 组件属性
export interface ApprovalListProps {
  title?: string;
  approvals: ApprovalListItem[];
  layout?: 'list' | 'cards' | 'compact';
  height?: string;
  showRefresh?: boolean;
  groupBy?: 'type' | 'priority' | 'agent' | 'none';
  emptyText?: string;
  showActions?: boolean;
}

// 类型配置
const typeConfig: Record<string, {
  label: string;
  icon: typeof Megaphone;
  color: string;
  bgColor: string;
}> = {
  marketing: {
    label: "营销活动",
    icon: Megaphone,
    color: "text-orange-500",
    bgColor: "bg-orange-500/10",
  },
  aftersales: {
    label: "售后申请",
    icon: Headphones,
    color: "text-blue-500",
    bgColor: "bg-blue-500/10",
  },
  flash_sale: {
    label: "限时抢购",
    icon: Zap,
    color: "text-yellow-500",
    bgColor: "bg-yellow-500/10",
  },
  group_buy: {
    label: "拼团活动",
    icon: Users,
    color: "text-purple-500",
    bgColor: "bg-purple-500/10",
  },
  product: {
    label: "商品审核",
    icon: Package,
    color: "text-green-500",
    bgColor: "bg-green-500/10",
  },
};

// 优先级配置
const priorityConfig: Record<string, { label: string; color: string }> = {
  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" },
};

interface GenUIApprovalListProps {
  props: ApprovalListProps;
  context: RenderContext;
}

export function ApprovalList({ props, context }: GenUIApprovalListProps) {
  const {
    title = "待审批",
    approvals,
    layout = 'list',
    height = "400px",
    showRefresh = true,
    groupBy = 'none',
    emptyText = "暂无待审批项",
    showActions = true,
  } = props;

  const getConfig = (type: string) => typeConfig[type] || typeConfig.marketing;
  const getPriority = (priority: string) => priorityConfig[priority] || priorityConfig.medium;

  // 分组逻辑
  const groupedApprovals = groupBy !== 'none'
    ? approvals.reduce((acc, item) => {
        const key = item[groupBy as keyof ApprovalListItem] as string || 'other';
        if (!acc[key]) acc[key] = [];
        acc[key].push(item);
        return acc;
      }, {} as Record<string, ApprovalListItem[]>)
    : { all: approvals };

  const renderApprovalItem = (item: ApprovalListItem) => {
    const config = getConfig(item.type);
    const priority = getPriority(item.priority);
    const Icon = config.icon;

    const isCompact = layout === 'compact';

    return (
      <div
        key={item.id}
        className={`rounded-lg border bg-card hover:shadow-md transition-all ${isCompact ? 'p-2' : 'p-4'}`}
      >
        <div className="flex items-start gap-3">
          <div className={`${isCompact ? 'h-8 w-8' : 'h-10 w-10'} rounded-full ${config.bgColor} flex items-center justify-center flex-shrink-0`}>
            <Icon className={`${isCompact ? 'h-4 w-4' : '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 truncate ${isCompact ? 'text-xs' : 'text-sm'}`}>{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" />
                {item.agent}
              </Badge>
            </div>

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

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

            {showActions && (
              <div className="flex items-center justify-between mt-2">
                {item.timestamp && (
                  <span className="text-xs text-muted-foreground">
                    {item.timestamp}
                  </span>
                )}

                <div className="flex items-center gap-2">
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-7 text-xs"
                    onClick={() => context.onAction?.('approval.view', { id: item.id })}
                  >
                    详情
                    <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={() => context.onAction?.('approval.reject', { id: item.id, type: item.type })}
                  >
                    <XCircle className="h-3 w-3 mr-1" />
                    拒绝
                  </Button>
                  <Button
                    size="sm"
                    variant="default"
                    className="h-7 text-xs"
                    onClick={() => context.onAction?.('approval.approve', { id: item.id, type: item.type })}
                  >
                    <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;

  const layoutClass = layout === 'cards'
    ? 'grid grid-cols-2 gap-3'
    : 'space-y-3';

  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">{title}</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>
            {showRefresh && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => context.onAction?.('approval.refresh')}
                disabled={context.loading}
              >
                <RefreshCw className={`h-4 w-4 ${context.loading ? 'animate-spin' : ''}`} />
              </Button>
            )}
          </div>
        </div>
      </CardHeader>

      <CardContent className="p-0">
        <ScrollArea style={{ height }}>
          <div className="p-4 pt-0">
            {approvals.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <CheckCircle2 className="h-12 w-12 mb-3 opacity-20" />
                <p>{emptyText}</p>
              </div>
            ) : groupBy !== 'none' ? (
              Object.entries(groupedApprovals).map(([group, items]) => (
                <div key={group} className="mb-4">
                  <h5 className="text-xs font-medium text-muted-foreground uppercase mb-2 flex items-center gap-2">
                    {group}
                    <Badge variant="outline" className="text-xs">{items.length}</Badge>
                  </h5>
                  <div className={layoutClass}>
                    {items.map(renderApprovalItem)}
                  </div>
                </div>
              ))
            ) : (
              <div className={layoutClass}>
                {approvals.map(renderApprovalItem)}
              </div>
            )}
          </div>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}
