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 { 
  Lightbulb, TrendingDown, TrendingUp, Zap, 
  CheckCircle2, AlertTriangle, ArrowRight, Clock,
  AlertCircle, BarChart3, RefreshCw
} from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";

// 统一洞察类型
export interface UnifiedInsight {
  id: string;
  type: 'opportunity' | 'warning' | 'auto_executed' | 'suggestion' | 'success' | 'info' | 'alert' | 'trend' | 'feedback';
  title: string;
  description: string;
  metric?: {
    label: string;
    value: string;
    trend?: 'up' | 'down' | 'neutral';
  };
  action?: {
    label: string;
    onClick?: () => void;
  };
  timestamp?: Date | string;
  time?: string; // 兼容旧格式
  priority?: 'low' | 'medium' | 'high' | 'urgent';
  impact?: 'low' | 'medium' | 'high';
  agent?: string; // 来源 Agent
  status?: 'pending' | 'executed' | 'dismissed';
  suggestedAction?: string;
}

interface UnifiedInsightFeedProps {
  title?: string;
  insights: UnifiedInsight[];
  loading?: boolean;
  height?: string;
  onAction?: (insightId: string, action: string) => void;
  onCreateCampaign?: (insight: UnifiedInsight) => void;
  onClick?: (insight: UnifiedInsight) => void;
  onRefresh?: () => void;
  showRefreshButton?: boolean;
  emptyText?: string;
  emptySubText?: string;
}

// 类型配置 - 统一所有类型的样式
const typeConfig: Record<string, {
  icon: typeof Lightbulb;
  color: string;
  bgColor: string;
  borderColor: string;
  label: string;
}> = {
  opportunity: {
    icon: Lightbulb,
    color: "text-amber-500",
    bgColor: "bg-amber-500/10",
    borderColor: "border-amber-500/30",
    label: "发现机会"
  },
  warning: {
    icon: AlertTriangle,
    color: "text-destructive",
    bgColor: "bg-destructive/10",
    borderColor: "border-destructive/30",
    label: "异常预警"
  },
  auto_executed: {
    icon: CheckCircle2,
    color: "text-emerald-500",
    bgColor: "bg-emerald-500/10",
    borderColor: "border-emerald-500/30",
    label: "自动执行"
  },
  suggestion: {
    icon: Zap,
    color: "text-primary",
    bgColor: "bg-primary/10",
    borderColor: "border-primary/30",
    label: "AI建议"
  },
  success: {
    icon: TrendingUp,
    color: "text-emerald-600",
    bgColor: "bg-emerald-50 dark:bg-emerald-950",
    borderColor: "border-emerald-200 dark:border-emerald-800",
    label: "正向趋势"
  },
  info: {
    icon: BarChart3,
    color: "text-blue-600",
    bgColor: "bg-blue-50 dark:bg-blue-950",
    borderColor: "border-blue-200 dark:border-blue-800",
    label: "数据分析"
  },
  alert: {
    icon: AlertCircle,
    color: "text-red-500",
    bgColor: "bg-red-50 dark:bg-red-950",
    borderColor: "border-red-200 dark:border-red-800",
    label: "紧急提醒"
  },
  trend: {
    icon: TrendingUp,
    color: "text-emerald-500",
    bgColor: "bg-emerald-50 dark:bg-emerald-950",
    borderColor: "border-emerald-200 dark:border-emerald-800",
    label: "趋势洞察"
  },
  feedback: {
    icon: CheckCircle2,
    color: "text-blue-500",
    bgColor: "bg-blue-50 dark:bg-blue-950",
    borderColor: "border-blue-200 dark:border-blue-800",
    label: "反馈"
  }
};

// 优先级配置
const priorityConfig: Record<string, string> = {
  urgent: "text-red-500 bg-red-50 dark:bg-red-950 border-red-200 dark:border-red-800",
  high: "text-orange-500 bg-orange-50 dark:bg-orange-950 border-orange-200 dark:border-orange-800",
  medium: "text-amber-500 bg-amber-50 dark:bg-amber-950 border-amber-200 dark:border-amber-800",
  low: "text-blue-500 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800"
};

export function UnifiedInsightFeed({
  title = "AI洞察",
  insights,
  loading = false,
  height = "320px",
  onAction,
  onCreateCampaign,
  onClick,
  onRefresh,
  showRefreshButton = true,
  emptyText = "暂无洞察",
  emptySubText = "点击刷新生成AI洞察"
}: UnifiedInsightFeedProps) {
  
  const getTimestamp = (insight: UnifiedInsight): string => {
    if (insight.time) return insight.time;
    if (insight.timestamp) {
      try {
        const date = typeof insight.timestamp === 'string' 
          ? new Date(insight.timestamp) 
          : insight.timestamp;
        // Validate the date is valid before formatting
        if (isNaN(date.getTime())) {
          return '';
        }
        return formatDistanceToNow(date, { addSuffix: true, locale: zhCN });
      } catch {
        return '';
      }
    }
    return '';
  };

  const getConfig = (type: string) => {
    return typeConfig[type] || typeConfig.info;
  };

  const getPriorityClass = (priority?: string) => {
    if (!priority) return '';
    return priorityConfig[priority] || '';
  };

  return (
    <Card className="h-full">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <Lightbulb className="h-4 w-4 text-amber-500" />
            {title}
            <Badge variant="secondary" className="ml-1">{insights.length}</Badge>
          </CardTitle>
          {showRefreshButton && onRefresh && (
            <Button 
              variant="ghost" 
              size="sm" 
              onClick={onRefresh}
              disabled={loading}
            >
              <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="p-0">
        <ScrollArea style={{ height }}>
          <div className="space-y-2 p-4 pt-0">
            {loading && insights.length === 0 ? (
              <div className="flex items-center justify-center py-12 text-muted-foreground">
                <RefreshCw className="h-5 w-5 animate-spin mr-2" />
                正在生成洞察...
              </div>
            ) : insights.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <Lightbulb className="h-12 w-12 mb-3 opacity-20" />
                <p>{emptyText}</p>
                <p className="text-sm mt-1">{emptySubText}</p>
              </div>
            ) : (
              insights.map((insight) => {
                const config = getConfig(insight.type);
                const InsightIcon = config.icon;
                const priorityClass = getPriorityClass(insight.priority);
                const isClickable = !!onClick;
                
                return (
                  <div
                    key={insight.id}
                    onClick={() => onClick?.(insight)}
                    className={`p-3 rounded-lg border transition-all ${
                      priorityClass || `${config.bgColor} ${config.borderColor}`
                    } ${isClickable ? 'cursor-pointer hover:shadow-sm hover:border-primary/50' : ''}`}
                  >
                    <div className="flex items-start gap-3">
                      <div className={`p-1.5 rounded-full ${config.bgColor}`}>
                        <InsightIcon className={`h-4 w-4 ${config.color}`} />
                      </div>
                      
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between gap-2 mb-1">
                          <div className="flex items-center gap-2 min-w-0">
                            <h4 className="font-medium text-sm truncate">{insight.title}</h4>
                            {insight.agent && (
                              <Badge variant="outline" className="text-xs shrink-0">{insight.agent}</Badge>
                            )}
                          </div>
                          <div className="flex items-center gap-1 shrink-0">
                            <span className="text-xs text-muted-foreground whitespace-nowrap">
                              {getTimestamp(insight)}
                            </span>
                            {isClickable && (
                              <ArrowRight className="h-3 w-3 text-muted-foreground" />
                            )}
                          </div>
                        </div>
                        
                        <p className="text-xs text-muted-foreground line-clamp-2">
                          {insight.description}
                        </p>
                        
                        {insight.metric && (
                          <div className="flex items-center gap-2 mt-2 text-xs">
                            <span className="text-muted-foreground">{insight.metric.label}:</span>
                            <span className="font-medium">{insight.metric.value}</span>
                            {insight.metric.trend === 'up' && (
                              <TrendingUp className="h-3 w-3 text-emerald-500" />
                            )}
                            {insight.metric.trend === 'down' && (
                              <TrendingDown className="h-3 w-3 text-destructive" />
                            )}
                          </div>
                        )}
                        
                        {/* 操作按钮区域 */}
                        {insight.type !== 'auto_executed' && (insight.action || insight.suggestedAction) && (
                          <div className="flex items-center gap-2 mt-2">
                            <Button
                              size="sm"
                              variant="ghost"
                              className="h-6 text-xs px-2"
                              onClick={(e) => {
                                e.stopPropagation();
                                if (insight.action?.onClick) {
                                  insight.action.onClick();
                                } else if (onCreateCampaign) {
                                  onCreateCampaign(insight);
                                }
                              }}
                            >
                              {insight.action?.label || insight.suggestedAction}
                              <ArrowRight className="h-3 w-3 ml-1" />
                            </Button>
                            {onAction && (
                              <Button
                                size="sm"
                                variant="ghost"
                                className="h-6 text-xs px-2"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  onAction(insight.id, 'dismiss');
                                }}
                              >
                                稍后处理
                              </Button>
                            )}
                          </div>
                        )}
                        
                        {insight.type === 'auto_executed' && (
                          <div className="flex items-center gap-2 mt-2">
                            <Badge variant="secondary" className="text-xs bg-emerald-500/20 text-emerald-600">
                              <CheckCircle2 className="h-3 w-3 mr-1" />
                              已自动执行
                            </Badge>
                            {onAction && (
                              <Button
                                size="sm"
                                variant="link"
                                className="h-auto p-0 text-xs"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  onAction(insight.id, 'view_details');
                                }}
                              >
                                查看详情
                              </Button>
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}
