/**
 * Agent 思考过程可视化组件
 * 展示 AI Agent 的推理链、决策过程和置信度
 */

import { useState, useEffect } from 'react';
import { cn } from '@/lib/utils';
import { 
  Brain, 
  Lightbulb, 
  Search, 
  Database, 
  CheckCircle2, 
  ArrowRight,
  Loader2,
  ChevronDown,
  ChevronUp,
  Sparkles
} from 'lucide-react';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';

export interface ThinkingStep {
  id: string;
  type: 'analyze' | 'search' | 'reason' | 'decide' | 'execute';
  label: string;
  description?: string;
  status: 'pending' | 'active' | 'completed';
  duration?: number; // ms
}

export interface AgentThinkingProcessProps {
  steps: ThinkingStep[];
  isThinking: boolean;
  confidence?: number; // 0-100
  reasoning?: string;
  className?: string;
  compact?: boolean;
  onExpand?: () => void;
}

const STEP_ICONS = {
  analyze: Brain,
  search: Search,
  reason: Lightbulb,
  decide: Database,
  execute: CheckCircle2,
};

const STEP_COLORS = {
  analyze: 'text-purple-500 bg-purple-100 dark:bg-purple-900/30',
  search: 'text-blue-500 bg-blue-100 dark:bg-blue-900/30',
  reason: 'text-amber-500 bg-amber-100 dark:bg-amber-900/30',
  decide: 'text-emerald-500 bg-emerald-100 dark:bg-emerald-900/30',
  execute: 'text-primary bg-primary/10',
};

export function AgentThinkingProcess({
  steps,
  isThinking,
  confidence,
  reasoning,
  className,
  compact = false,
  onExpand,
}: AgentThinkingProcessProps) {
  const [expanded, setExpanded] = useState(!compact);
  const [animatedConfidence, setAnimatedConfidence] = useState(0);

  // 动画置信度
  useEffect(() => {
    if (confidence !== undefined) {
      const timer = setTimeout(() => {
        setAnimatedConfidence(confidence);
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [confidence]);

  const activeStep = steps.find(s => s.status === 'active');
  const completedSteps = steps.filter(s => s.status === 'completed').length;

  if (compact && !expanded) {
    return (
      <div 
        className={cn(
          "flex items-center gap-2 p-2 rounded-lg bg-muted/50 cursor-pointer hover:bg-muted transition-colors",
          className
        )}
        onClick={() => setExpanded(true)}
      >
        {isThinking ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin text-primary" />
            <span className="text-xs text-muted-foreground">
              {activeStep?.label || '思考中...'}
            </span>
          </>
        ) : (
          <>
            <Sparkles className="h-4 w-4 text-primary" />
            <span className="text-xs text-muted-foreground">
              已完成 {completedSteps}/{steps.length} 步
            </span>
            {confidence !== undefined && (
              <Badge variant="secondary" className="text-xs ml-auto">
                置信度 {confidence}%
              </Badge>
            )}
          </>
        )}
        <ChevronDown className="h-4 w-4 text-muted-foreground ml-auto" />
      </div>
    );
  }

  return (
    <div className={cn("rounded-lg border bg-card overflow-hidden", className)}>
      {/* Header */}
      <div className="flex items-center justify-between p-3 border-b bg-muted/30">
        <div className="flex items-center gap-2">
          {isThinking ? (
            <Loader2 className="h-4 w-4 animate-spin text-primary" />
          ) : (
            <Brain className="h-4 w-4 text-primary" />
          )}
          <span className="text-sm font-medium">
            {isThinking ? 'Agent 思考中...' : 'Agent 推理过程'}
          </span>
        </div>
        
        <div className="flex items-center gap-2">
          {confidence !== undefined && (
            <div className="flex items-center gap-1.5">
              <span className="text-xs text-muted-foreground">置信度</span>
              <div className="w-16 h-1.5 bg-muted rounded-full overflow-hidden">
                <div 
                  className="h-full bg-primary rounded-full transition-all duration-500"
                  style={{ width: `${animatedConfidence}%` }}
                />
              </div>
              <span className="text-xs font-medium w-8">{confidence}%</span>
            </div>
          )}
          
          {compact && (
            <Button
              variant="ghost"
              size="sm"
              className="h-6 w-6 p-0"
              onClick={() => setExpanded(false)}
            >
              <ChevronUp className="h-4 w-4" />
            </Button>
          )}
        </div>
      </div>

      {/* Steps */}
      <div className="p-3 space-y-2">
        {steps.map((step, index) => {
          const Icon = STEP_ICONS[step.type];
          const colorClass = STEP_COLORS[step.type];
          const isActive = step.status === 'active';
          const isCompleted = step.status === 'completed';
          
          return (
            <div key={step.id} className="flex items-start gap-3">
              {/* Step indicator */}
              <div className="flex flex-col items-center">
                <div 
                  className={cn(
                    "w-7 h-7 rounded-full flex items-center justify-center transition-all",
                    isActive && "ring-2 ring-primary ring-offset-2",
                    isCompleted ? colorClass : "bg-muted text-muted-foreground"
                  )}
                >
                  {isActive ? (
                    <Loader2 className="h-3.5 w-3.5 animate-spin" />
                  ) : isCompleted ? (
                    <Icon className="h-3.5 w-3.5" />
                  ) : (
                    <span className="text-xs">{index + 1}</span>
                  )}
                </div>
                
                {/* Connector line */}
                {index < steps.length - 1 && (
                  <div 
                    className={cn(
                      "w-0.5 h-4 mt-1",
                      isCompleted ? "bg-primary/50" : "bg-muted"
                    )}
                  />
                )}
              </div>
              
              {/* Step content */}
              <div className="flex-1 pb-2">
                <div className="flex items-center gap-2">
                  <span 
                    className={cn(
                      "text-sm font-medium",
                      isActive && "text-primary",
                      !isActive && !isCompleted && "text-muted-foreground"
                    )}
                  >
                    {step.label}
                  </span>
                  {isCompleted && step.duration && (
                    <span className="text-xs text-muted-foreground">
                      {step.duration}ms
                    </span>
                  )}
                </div>
                {step.description && (
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {step.description}
                  </p>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Reasoning summary */}
      {reasoning && !isThinking && (
        <div className="px-3 pb-3">
          <div className="p-2.5 rounded-lg bg-primary/5 border border-primary/10">
            <div className="flex items-start gap-2">
              <Lightbulb className="h-4 w-4 text-primary shrink-0 mt-0.5" />
              <div>
                <p className="text-xs font-medium text-primary mb-1">推理结论</p>
                <p className="text-xs text-muted-foreground">{reasoning}</p>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/**
 * 简化版思考指示器 - 用于内联展示
 */
export function ThinkingIndicator({ 
  label = "思考中",
  className 
}: { 
  label?: string;
  className?: string;
}) {
  return (
    <div className={cn("flex items-center gap-2", className)}>
      <div className="relative">
        <Brain className="h-4 w-4 text-primary" />
        <span className="absolute -top-0.5 -right-0.5 flex h-2 w-2">
          <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"></span>
          <span className="relative inline-flex rounded-full h-2 w-2 bg-primary"></span>
        </span>
      </div>
      <span className="text-xs text-muted-foreground animate-pulse">{label}</span>
    </div>
  );
}

/**
 * Agent 置信度徽章
 */
export function ConfidenceBadge({ 
  confidence,
  className 
}: { 
  confidence: number;
  className?: string;
}) {
  const getConfidenceColor = () => {
    if (confidence >= 90) return "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400";
    if (confidence >= 70) return "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400";
    if (confidence >= 50) return "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400";
    return "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400";
  };

  return (
    <Badge 
      variant="secondary" 
      className={cn("text-xs font-medium", getConfidenceColor(), className)}
    >
      <Sparkles className="h-3 w-3 mr-1" />
      {confidence}% 置信度
    </Badge>
  );
}

export default AgentThinkingProcess;
