/**
 * 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 { 
  Lightbulb, TrendingDown, TrendingUp, Zap, 
  CheckCircle2, AlertTriangle, ArrowRight,
  AlertCircle, BarChart3, RefreshCw
} from "lucide-react";
import type { RenderContext } from '../types';

// 洞察项类型
export interface InsightItem {
  id: string;
  type: 'opportunity' | 'warning' | 'auto_executed' | 'suggestion' | 'success' | 'info' | 'alert' | 'trend';
  title: string;
  description: string;
  metric?: {
    label: string;
    value: string;
    trend?: 'up' | 'down' | 'neutral';
  };
  actionLabel?: string;
  actionId?: string;
  timestamp?: string;
  priority?: 'low' | 'medium' | 'high' | 'urgent';
  agent?: string;
}

// 组件属性
export interface InsightFeedProps {
  title?: string;
  insights: InsightItem[];
  layout?: 'list' | 'grid' | 'compact';
  height?: string;
  showRefresh?: boolean;
  emptyText?: string;
  groupBy?: 'type' | 'priority' | 'agent' | 'none';
}

// 类型配置
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: "趋势洞察"
  }
};

// 优先级配置
const priorityConfig: Record<string, string> = {
  urgent: "border-l-4 border-l-red-500",
  high: "border-l-4 border-l-orange-500",
  medium: "border-l-4 border-l-amber-500",
  low: "border-l-4 border-l-blue-500"
};

interface GenUIInsightFeedProps {
  props: InsightFeedProps;
  context: RenderContext;
}

export function InsightFeed({ props, context }: GenUIInsightFeedProps) {
  const { 
    title = "AI洞察", 
    insights, 
    layout = 'list',
    height = "320px",
    showRefresh = true,
    emptyText = "暂无洞察",
    groupBy = 'none'
  } = props;

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

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

  const renderInsight = (insight: InsightItem) => {
    const config = getConfig(insight.type);
    const InsightIcon = config.icon;
    const priorityClass = insight.priority ? priorityConfig[insight.priority] : '';

    return (
      <div
        key={insight.id}
        className={`p-3 rounded-lg border transition-all cursor-pointer hover:shadow-sm ${config.bgColor} ${config.borderColor} ${priorityClass}`}
        onClick={() => context.onAction?.('insight.click', { insightId: insight.id })}
      >
        <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>
              {insight.timestamp && (
                <span className="text-xs text-muted-foreground whitespace-nowrap">
                  {insight.timestamp}
                </span>
              )}
            </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.actionLabel && insight.type !== 'auto_executed' && (
              <Button
                size="sm"
                variant="ghost"
                className="h-6 text-xs px-2 mt-2"
                onClick={(e) => {
                  e.stopPropagation();
                  context.onAction?.('insight.action', { 
                    insightId: insight.id, 
                    actionId: insight.actionId 
                  });
                }}
              >
                {insight.actionLabel}
                <ArrowRight className="h-3 w-3 ml-1" />
              </Button>
            )}
            
            {insight.type === 'auto_executed' && (
              <Badge variant="secondary" className="text-xs bg-emerald-500/20 text-emerald-600 mt-2">
                <CheckCircle2 className="h-3 w-3 mr-1" />
                已自动执行
              </Badge>
            )}
          </div>
        </div>
      </div>
    );
  };

  const layoutClass = layout === 'grid' 
    ? 'grid grid-cols-2 gap-2' 
    : layout === 'compact' 
      ? 'space-y-1' 
      : 'space-y-2';

  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>
          {showRefresh && (
            <Button 
              variant="ghost" 
              size="sm" 
              onClick={() => context.onAction?.('insight.refresh')}
              disabled={context.loading}
            >
              <RefreshCw className={`h-4 w-4 ${context.loading ? 'animate-spin' : ''}`} />
            </Button>
          )}
        </div>
      </CardHeader>
      <CardContent className="p-0">
        <ScrollArea style={{ height }}>
          <div className="p-4 pt-0">
            {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>
              </div>
            ) : groupBy !== 'none' ? (
              Object.entries(groupedInsights).map(([group, items]) => (
                <div key={group} className="mb-4">
                  <h5 className="text-xs font-medium text-muted-foreground uppercase mb-2">
                    {group}
                  </h5>
                  <div className={layoutClass}>
                    {items.map(renderInsight)}
                  </div>
                </div>
              ))
            ) : (
              <div className={layoutClass}>
                {insights.map(renderInsight)}
              </div>
            )}
          </div>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}
