/**
 * 增强型洞察流组件 - 支持迷你图表、进度条、分组、展开详情等丰富功能
 */

import { useState } 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 { Progress } from "@/components/ui/progress";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { 
  Lightbulb, TrendingDown, TrendingUp, Zap, 
  CheckCircle2, AlertTriangle, ArrowRight, Clock,
  AlertCircle, BarChart3, RefreshCw, ChevronDown,
  ChevronRight, Target, Users, ShoppingCart,
  DollarSign, Package, MessageSquare, Star,
  Flame, Eye, ThumbsUp, Filter, Sparkles
} from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import { cn } from "@/lib/utils";

// 丰富的洞察类型
export type RichInsightType = 
  | 'opportunity' | 'warning' | 'auto_executed' | 'suggestion' 
  | 'success' | 'info' | 'alert' | 'trend' | 'feedback'
  | 'goal_progress' | 'anomaly' | 'prediction' | 'comparison'
  | 'customer_insight' | 'product_insight' | 'revenue_insight';

export type InsightPriority = 'low' | 'medium' | 'high' | 'urgent' | 'critical';
export type InsightCategory = 'sales' | 'customer' | 'product' | 'marketing' | 'finance' | 'service' | 'general';

export interface RichInsight {
  id: string;
  type: RichInsightType;
  category?: InsightCategory;
  title: string;
  description: string;
  
  // 指标数据
  metric?: {
    label: string;
    value: string | number;
    unit?: string;
    trend?: 'up' | 'down' | 'neutral';
    trendValue?: string;
    previousValue?: string | number;
  };
  
  // 进度数据
  progress?: {
    current: number;
    target: number;
    label?: string;
  };
  
  // 迷你图表数据
  sparkline?: number[];
  
  // 对比数据
  comparison?: {
    current: number;
    previous: number;
    label?: string;
  };
  
  // 标签
  tags?: string[];
  
  // 操作
  action?: {
    label: string;
    type?: 'primary' | 'secondary' | 'destructive';
    onClick?: () => void;
  };
  secondaryActions?: Array<{
    label: string;
    onClick?: () => void;
  }>;
  
  // 元数据
  timestamp?: Date | string;
  priority?: InsightPriority;
  impact?: 'low' | 'medium' | 'high';
  confidence?: number; // 0-100
  agent?: string;
  source?: string;
  
  // 展开内容
  expandedContent?: string;
  relatedInsights?: string[];
}

interface RichInsightStreamProps {
  title?: string;
  insights: RichInsight[];
  loading?: boolean;
  height?: string;
  groupByCategory?: boolean;
  showFilters?: boolean;
  onAction?: (insightId: string, action: string) => void;
  onClick?: (insight: RichInsight) => void;
  onRefresh?: () => void;
  showRefreshButton?: boolean;
  emptyText?: string;
  emptySubText?: string;
  className?: string;
}

// 类型配置
const typeConfig: Record<RichInsightType, {
  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-500/10",
    borderColor: "border-emerald-500/30",
    label: "正向趋势"
  },
  info: {
    icon: BarChart3,
    color: "text-blue-600",
    bgColor: "bg-blue-500/10",
    borderColor: "border-blue-500/30",
    label: "数据分析"
  },
  alert: {
    icon: AlertCircle,
    color: "text-red-500",
    bgColor: "bg-red-500/10",
    borderColor: "border-red-500/30",
    label: "紧急提醒"
  },
  trend: {
    icon: TrendingUp,
    color: "text-emerald-500",
    bgColor: "bg-emerald-500/10",
    borderColor: "border-emerald-500/30",
    label: "趋势洞察"
  },
  feedback: {
    icon: MessageSquare,
    color: "text-blue-500",
    bgColor: "bg-blue-500/10",
    borderColor: "border-blue-500/30",
    label: "反馈"
  },
  goal_progress: {
    icon: Target,
    color: "text-purple-500",
    bgColor: "bg-purple-500/10",
    borderColor: "border-purple-500/30",
    label: "目标进度"
  },
  anomaly: {
    icon: Flame,
    color: "text-orange-500",
    bgColor: "bg-orange-500/10",
    borderColor: "border-orange-500/30",
    label: "异常检测"
  },
  prediction: {
    icon: Sparkles,
    color: "text-indigo-500",
    bgColor: "bg-indigo-500/10",
    borderColor: "border-indigo-500/30",
    label: "AI预测"
  },
  comparison: {
    icon: BarChart3,
    color: "text-cyan-500",
    bgColor: "bg-cyan-500/10",
    borderColor: "border-cyan-500/30",
    label: "对比分析"
  },
  customer_insight: {
    icon: Users,
    color: "text-pink-500",
    bgColor: "bg-pink-500/10",
    borderColor: "border-pink-500/30",
    label: "客户洞察"
  },
  product_insight: {
    icon: Package,
    color: "text-teal-500",
    bgColor: "bg-teal-500/10",
    borderColor: "border-teal-500/30",
    label: "商品洞察"
  },
  revenue_insight: {
    icon: DollarSign,
    color: "text-green-500",
    bgColor: "bg-green-500/10",
    borderColor: "border-green-500/30",
    label: "营收洞察"
  }
};

// 分类配置
const categoryConfig: Record<InsightCategory, {
  icon: typeof ShoppingCart;
  label: string;
  color: string;
}> = {
  sales: { icon: ShoppingCart, label: "销售", color: "text-emerald-500" },
  customer: { icon: Users, label: "客户", color: "text-blue-500" },
  product: { icon: Package, label: "商品", color: "text-purple-500" },
  marketing: { icon: Star, label: "营销", color: "text-amber-500" },
  finance: { icon: DollarSign, label: "财务", color: "text-green-500" },
  service: { icon: MessageSquare, label: "服务", color: "text-pink-500" },
  general: { icon: Lightbulb, label: "综合", color: "text-muted-foreground" }
};

// 优先级配置
const priorityConfig: Record<InsightPriority, {
  label: string;
  color: string;
  bgColor: string;
}> = {
  critical: { label: "紧急", color: "text-red-600", bgColor: "bg-red-500/20" },
  urgent: { label: "高优", color: "text-orange-600", bgColor: "bg-orange-500/20" },
  high: { label: "重要", color: "text-amber-600", bgColor: "bg-amber-500/20" },
  medium: { label: "中等", color: "text-blue-600", bgColor: "bg-blue-500/20" },
  low: { label: "一般", color: "text-muted-foreground", bgColor: "bg-muted" }
};

// 迷你 Sparkline 组件
function MiniSparkline({ data, className }: { data: number[]; className?: string }) {
  if (!data || data.length < 2) return null;
  
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const height = 24;
  const width = 60;
  const points = data.map((v, i) => {
    const x = (i / (data.length - 1)) * width;
    const y = height - ((v - min) / range) * height;
    return `${x},${y}`;
  }).join(' ');
  
  const isUp = data[data.length - 1] > data[0];
  
  return (
    <svg 
      className={cn("flex-shrink-0", className)} 
      width={width} 
      height={height} 
      viewBox={`0 0 ${width} ${height}`}
    >
      <polyline
        points={points}
        fill="none"
        stroke={isUp ? "hsl(var(--chart-2))" : "hsl(var(--destructive))"}
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

// 对比条组件
function ComparisonBar({ current, previous, label }: { current: number; previous: number; label?: string }) {
  const max = Math.max(current, previous);
  const currentPercent = (current / max) * 100;
  const previousPercent = (previous / max) * 100;
  const change = previous > 0 ? ((current - previous) / previous) * 100 : 0;
  
  return (
    <div className="space-y-1.5 mt-2">
      {label && <span className="text-xs text-muted-foreground">{label}</span>}
      <div className="flex items-center gap-2 text-xs">
        <span className="w-12 text-muted-foreground">本期</span>
        <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
          <div 
            className="h-full bg-primary rounded-full transition-all"
            style={{ width: `${currentPercent}%` }}
          />
        </div>
        <span className="w-16 text-right font-medium">{current.toLocaleString()}</span>
      </div>
      <div className="flex items-center gap-2 text-xs">
        <span className="w-12 text-muted-foreground">上期</span>
        <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
          <div 
            className="h-full bg-muted-foreground/30 rounded-full transition-all"
            style={{ width: `${previousPercent}%` }}
          />
        </div>
        <span className="w-16 text-right">{previous.toLocaleString()}</span>
      </div>
      <div className="flex justify-end">
        <span className={cn(
          "text-xs font-medium",
          change >= 0 ? "text-emerald-500" : "text-destructive"
        )}>
          {change >= 0 ? "+" : ""}{change.toFixed(1)}%
        </span>
      </div>
    </div>
  );
}

// 单个洞察卡片组件
function InsightItem({ 
  insight, 
  onClick, 
  onAction 
}: { 
  insight: RichInsight; 
  onClick?: (insight: RichInsight) => void;
  onAction?: (insightId: string, action: string) => void;
}) {
  const [isExpanded, setIsExpanded] = useState(false);
  
  const config = typeConfig[insight.type] || typeConfig.info;
  const InsightIcon = config.icon;
  const priorityCfg = insight.priority ? priorityConfig[insight.priority] : null;
  
  const getTimestamp = (): string => {
    if (!insight.timestamp) return '';
    const date = typeof insight.timestamp === 'string' 
      ? new Date(insight.timestamp) 
      : insight.timestamp;
    return formatDistanceToNow(date, { addSuffix: true, locale: zhCN });
  };
  
  const hasExpandableContent = insight.expandedContent || insight.comparison;
  
  return (
    <Collapsible open={isExpanded} onOpenChange={setIsExpanded}>
      <div
        className={cn(
          "p-3 rounded-lg border transition-all",
          config.bgColor,
          config.borderColor,
          onClick ? "cursor-pointer hover:shadow-md hover:border-primary/50" : ""
        )}
      >
        <div className="flex items-start gap-3">
          {/* 图标 */}
          <div className={cn("p-1.5 rounded-full", config.bgColor)}>
            <InsightIcon className={cn("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 flex-wrap">
                <h4 
                  className="font-medium text-sm truncate cursor-pointer"
                  onClick={() => onClick?.(insight)}
                >
                  {insight.title}
                </h4>
                {priorityCfg && (
                  <Badge variant="secondary" className={cn("text-xs", priorityCfg.bgColor, priorityCfg.color)}>
                    {priorityCfg.label}
                  </Badge>
                )}
                {insight.agent && (
                  <Badge variant="outline" className="text-xs">{insight.agent}</Badge>
                )}
              </div>
              <div className="flex items-center gap-2 shrink-0">
                {insight.confidence && (
                  <span className="text-xs text-muted-foreground">
                    可信度 {insight.confidence}%
                  </span>
                )}
                <span className="text-xs text-muted-foreground whitespace-nowrap">
                  {getTimestamp()}
                </span>
                {hasExpandableContent && (
                  <CollapsibleTrigger asChild>
                    <Button variant="ghost" size="sm" className="h-6 w-6 p-0">
                      {isExpanded ? (
                        <ChevronDown className="h-3 w-3" />
                      ) : (
                        <ChevronRight className="h-3 w-3" />
                      )}
                    </Button>
                  </CollapsibleTrigger>
                )}
              </div>
            </div>
            
            {/* 描述 */}
            <p className="text-xs text-muted-foreground line-clamp-2">
              {insight.description}
            </p>
            
            {/* 标签 */}
            {insight.tags && insight.tags.length > 0 && (
              <div className="flex flex-wrap gap-1 mt-2">
                {insight.tags.map((tag, i) => (
                  <Badge key={i} variant="secondary" className="text-xs px-1.5 py-0">
                    {tag}
                  </Badge>
                ))}
              </div>
            )}
            
            {/* 指标 + Sparkline */}
            {(insight.metric || insight.sparkline) && (
              <div className="flex items-center justify-between gap-3 mt-2">
                {insight.metric && (
                  <div className="flex items-center gap-2 text-xs">
                    <span className="text-muted-foreground">{insight.metric.label}:</span>
                    <span className="font-semibold">
                      {insight.metric.value}{insight.metric.unit || ''}
                    </span>
                    {insight.metric.trend === 'up' && (
                      <span className="flex items-center text-emerald-500">
                        <TrendingUp className="h-3 w-3 mr-0.5" />
                        {insight.metric.trendValue}
                      </span>
                    )}
                    {insight.metric.trend === 'down' && (
                      <span className="flex items-center text-destructive">
                        <TrendingDown className="h-3 w-3 mr-0.5" />
                        {insight.metric.trendValue}
                      </span>
                    )}
                  </div>
                )}
                {insight.sparkline && (
                  <MiniSparkline data={insight.sparkline} />
                )}
              </div>
            )}
            
            {/* 进度条 */}
            {insight.progress && (
              <div className="mt-2 space-y-1">
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">{insight.progress.label || "进度"}</span>
                  <span className="font-medium">
                    {insight.progress.current} / {insight.progress.target}
                    <span className="text-muted-foreground ml-1">
                      ({Math.round((insight.progress.current / insight.progress.target) * 100)}%)
                    </span>
                  </span>
                </div>
                <Progress 
                  value={(insight.progress.current / insight.progress.target) * 100} 
                  className="h-1.5"
                />
              </div>
            )}
            
            {/* 展开内容 */}
            <CollapsibleContent>
              {insight.expandedContent && (
                <div className="mt-3 pt-3 border-t border-border/50 text-xs text-muted-foreground">
                  {insight.expandedContent}
                </div>
              )}
              {insight.comparison && (
                <ComparisonBar 
                  current={insight.comparison.current}
                  previous={insight.comparison.previous}
                  label={insight.comparison.label}
                />
              )}
            </CollapsibleContent>
            
            {/* 操作按钮 */}
            {(insight.action || insight.secondaryActions) && insight.type !== 'auto_executed' && (
              <div className="flex items-center gap-2 mt-3">
                {insight.action && (
                  <Button
                    size="sm"
                    variant={insight.action.type === 'primary' ? 'default' : 'ghost'}
                    className="h-7 text-xs"
                    onClick={(e) => {
                      e.stopPropagation();
                      insight.action?.onClick?.();
                    }}
                  >
                    {insight.action.label}
                    <ArrowRight className="h-3 w-3 ml-1" />
                  </Button>
                )}
                {insight.secondaryActions?.map((action, i) => (
                  <Button
                    key={i}
                    size="sm"
                    variant="ghost"
                    className="h-7 text-xs"
                    onClick={(e) => {
                      e.stopPropagation();
                      action.onClick?.();
                    }}
                  >
                    {action.label}
                  </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>
    </Collapsible>
  );
}

// 分组标题组件
function CategoryHeader({ 
  category, 
  count,
  isExpanded,
  onToggle
}: { 
  category: InsightCategory; 
  count: number;
  isExpanded: boolean;
  onToggle: () => void;
}) {
  const cfg = categoryConfig[category];
  const CategoryIcon = cfg.icon;
  
  return (
    <button
      onClick={onToggle}
      className="flex items-center gap-2 w-full py-2 px-1 hover:bg-muted/50 rounded-md transition-colors"
    >
      {isExpanded ? (
        <ChevronDown className="h-4 w-4 text-muted-foreground" />
      ) : (
        <ChevronRight className="h-4 w-4 text-muted-foreground" />
      )}
      <CategoryIcon className={cn("h-4 w-4", cfg.color)} />
      <span className="font-medium text-sm">{cfg.label}</span>
      <Badge variant="secondary" className="text-xs">{count}</Badge>
    </button>
  );
}

export function RichInsightStream({
  title = "智能洞察",
  insights,
  loading = false,
  height = "400px",
  groupByCategory = false,
  showFilters = false,
  onAction,
  onClick,
  onRefresh,
  showRefreshButton = true,
  emptyText = "暂无洞察",
  emptySubText = "点击刷新获取 AI 智能分析",
  className
}: RichInsightStreamProps) {
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set(['sales', 'customer', 'product', 'marketing', 'finance', 'service', 'general']));
  const [filterType, setFilterType] = useState<RichInsightType | 'all'>('all');
  
  const toggleCategory = (category: string) => {
    const newSet = new Set(expandedCategories);
    if (newSet.has(category)) {
      newSet.delete(category);
    } else {
      newSet.add(category);
    }
    setExpandedCategories(newSet);
  };
  
  // 过滤洞察
  const filteredInsights = filterType === 'all' 
    ? insights 
    : insights.filter(i => i.type === filterType);
  
  // 按分类分组
  const groupedInsights = groupByCategory
    ? filteredInsights.reduce((acc, insight) => {
        const cat = insight.category || 'general';
        if (!acc[cat]) acc[cat] = [];
        acc[cat].push(insight);
        return acc;
      }, {} as Record<InsightCategory, RichInsight[]>)
    : null;
  
  const uniqueTypes = [...new Set(insights.map(i => i.type))];
  
  return (
    <Card className={cn("h-full", className)}>
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            {title}
            <Badge variant="secondary" className="ml-1">{filteredInsights.length}</Badge>
          </CardTitle>
          <div className="flex items-center gap-2">
            {showFilters && uniqueTypes.length > 1 && (
              <div className="flex items-center gap-1">
                <Filter className="h-3 w-3 text-muted-foreground" />
                <select
                  className="text-xs border rounded px-1.5 py-0.5 bg-background"
                  value={filterType}
                  onChange={(e) => setFilterType(e.target.value as RichInsightType | 'all')}
                >
                  <option value="all">全部</option>
                  {uniqueTypes.map(type => (
                    <option key={type} value={type}>{typeConfig[type]?.label || type}</option>
                  ))}
                </select>
              </div>
            )}
            {showRefreshButton && onRefresh && (
              <Button 
                variant="ghost" 
                size="sm" 
                onClick={onRefresh}
                disabled={loading}
              >
                <RefreshCw className={cn("h-4 w-4", loading && "animate-spin")} />
              </Button>
            )}
          </div>
        </div>
      </CardHeader>
      <CardContent className="p-0">
        <ScrollArea style={{ height }}>
          <div className="space-y-2 p-4 pt-0">
            {loading && filteredInsights.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <RefreshCw className="h-6 w-6 animate-spin mb-3" />
                <p>正在分析数据生成洞察...</p>
              </div>
            ) : filteredInsights.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <Sparkles className="h-12 w-12 mb-3 opacity-20" />
                <p>{emptyText}</p>
                <p className="text-sm mt-1">{emptySubText}</p>
              </div>
            ) : groupedInsights ? (
              // 分组视图
              Object.entries(groupedInsights).map(([category, categoryInsights]) => (
                <div key={category} className="mb-3">
                  <CategoryHeader
                    category={category as InsightCategory}
                    count={categoryInsights.length}
                    isExpanded={expandedCategories.has(category)}
                    onToggle={() => toggleCategory(category)}
                  />
                  {expandedCategories.has(category) && (
                    <div className="space-y-2 mt-2 ml-4">
                      {categoryInsights.map(insight => (
                        <InsightItem
                          key={insight.id}
                          insight={insight}
                          onClick={onClick}
                          onAction={onAction}
                        />
                      ))}
                    </div>
                  )}
                </div>
              ))
            ) : (
              // 列表视图
              filteredInsights.map(insight => (
                <InsightItem
                  key={insight.id}
                  insight={insight}
                  onClick={onClick}
                  onAction={onAction}
                />
              ))
            )}
          </div>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}

export default RichInsightStream;
