/**
 * Agent 状态 GenUI 组件
 * 用于动态渲染的 Agent 信息展示
 */

import { cn } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
  Bot,
  Zap,
  CheckCircle2,
  AlertCircle,
  TrendingUp,
  Brain,
  Activity,
  Settings,
  Sparkles
} from 'lucide-react';
import { AI_AGENTS } from '@/types/agents';
import type { RenderContext } from '../types';

// Agent 状态组件 Props
interface AgentStatusProps {
  props: {
    agentId: string;
    status: 'online' | 'busy' | 'offline';
    metrics?: Array<{
      label: string;
      value: string | number;
      trend?: 'up' | 'down' | 'neutral';
      change?: string;
    }>;
    lastActivity?: string;
    thinkingSteps?: Array<{
      id: string;
      label: string;
      status: 'pending' | 'active' | 'completed';
      duration?: number;
    }>;
    confidence?: number;
  };
  context: RenderContext;
}

const STATUS_CONFIG = {
  online: {
    label: '运行中',
    color: 'bg-emerald-500',
    textColor: 'text-emerald-600 dark:text-emerald-400',
    bgColor: 'bg-emerald-100 dark:bg-emerald-900/30',
  },
  busy: {
    label: '处理中',
    color: 'bg-amber-500',
    textColor: 'text-amber-600 dark:text-amber-400',
    bgColor: 'bg-amber-100 dark:bg-amber-900/30',
  },
  offline: {
    label: '离线',
    color: 'bg-muted-foreground',
    textColor: 'text-muted-foreground',
    bgColor: 'bg-muted',
  },
};

export function AgentStatus({ props, context }: AgentStatusProps) {
  const { agentId, status, metrics, lastActivity, thinkingSteps, confidence } = props;
  const agent = AI_AGENTS[agentId] || AI_AGENTS.service;
  const statusConfig = STATUS_CONFIG[status];

  return (
    <Card className="overflow-hidden">
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-3">
            <div className="relative">
              <Avatar className="h-12 w-12 border-2 border-background shadow-md">
                <AvatarImage src={agent.avatar} alt={agent.name} />
                <AvatarFallback className={agent.color}>
                  {agent.emoji}
                </AvatarFallback>
              </Avatar>
              <span className="absolute -bottom-0.5 -right-0.5 flex h-4 w-4">
                {status === 'online' && (
                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                )}
                <span className={cn("relative inline-flex rounded-full h-4 w-4 border-2 border-background", statusConfig.color)}></span>
              </span>
            </div>
            
            <div>
              <div className="flex items-center gap-2">
                <h3 className="font-semibold">{agent.name}</h3>
                <Badge variant="secondary" className={cn("text-xs", statusConfig.bgColor, statusConfig.textColor)}>
                  {statusConfig.label}
                </Badge>
              </div>
              <p className="text-sm text-muted-foreground">{agent.role}</p>
            </div>
          </div>
          
          {confidence !== undefined && (
            <Badge variant="outline" className="gap-1">
              <Sparkles className="h-3 w-3" />
              {confidence}% 置信度
            </Badge>
          )}
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        {/* Metrics */}
        {metrics && metrics.length > 0 && (
          <div className="grid grid-cols-3 gap-2">
            {metrics.slice(0, 3).map((metric, index) => (
              <div key={index} className="text-center p-2 rounded-lg bg-muted/50">
                <p className="text-lg font-semibold">{metric.value}</p>
                <p className="text-xs text-muted-foreground">{metric.label}</p>
                {metric.trend && (
                  <div className={cn(
                    "text-xs flex items-center justify-center gap-0.5 mt-0.5",
                    metric.trend === 'up' && "text-emerald-600",
                    metric.trend === 'down' && "text-red-600",
                    metric.trend === 'neutral' && "text-muted-foreground"
                  )}>
                    <TrendingUp className={cn(
                      "h-3 w-3",
                      metric.trend === 'down' && "rotate-180"
                    )} />
                    {metric.change}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {/* Thinking Steps */}
        {thinkingSteps && thinkingSteps.length > 0 && (
          <div className="space-y-2">
            <h4 className="text-sm font-medium flex items-center gap-1.5">
              <Brain className="h-4 w-4 text-primary" />
              推理过程
            </h4>
            <div className="space-y-1">
              {thinkingSteps.map((step, index) => (
                <div key={step.id} className="flex items-center gap-2 text-sm">
                  <div className={cn(
                    "w-5 h-5 rounded-full flex items-center justify-center text-xs",
                    step.status === 'completed' && "bg-primary text-primary-foreground",
                    step.status === 'active' && "bg-primary/20 text-primary animate-pulse",
                    step.status === 'pending' && "bg-muted text-muted-foreground"
                  )}>
                    {step.status === 'completed' ? '✓' : index + 1}
                  </div>
                  <span className={cn(
                    step.status === 'completed' && "text-foreground",
                    step.status === 'active' && "text-primary font-medium",
                    step.status === 'pending' && "text-muted-foreground"
                  )}>
                    {step.label}
                  </span>
                  {step.duration && (
                    <span className="text-xs text-muted-foreground ml-auto">
                      {step.duration}ms
                    </span>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Last Activity */}
        {lastActivity && (
          <div className="flex items-center gap-2 text-xs text-muted-foreground pt-2 border-t">
            <Activity className="h-3 w-3" />
            <span>最近活动: {lastActivity}</span>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// Agent 能力列表组件 Props
interface AgentCapabilitiesProps {
  props: {
    agentId: string;
    capabilities: Array<{
      id: string;
      name: string;
      description: string;
      enabled: boolean;
      usageToday?: number;
      limit?: number;
    }>;
  };
  context: RenderContext;
}

export function AgentCapabilities({ props, context }: AgentCapabilitiesProps) {
  const { agentId, capabilities } = props;
  const agent = AI_AGENTS[agentId] || AI_AGENTS.service;

  return (
    <Card>
      <CardHeader className="pb-3">
        <CardTitle className="text-base flex items-center gap-2">
          <Zap className="h-4 w-4 text-primary" />
          {agent.name} 能力
          <Badge variant="secondary" className="ml-auto text-xs">
            {capabilities.filter(c => c.enabled).length}/{capabilities.length} 已启用
          </Badge>
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-2">
        {capabilities.map((capability) => (
          <div 
            key={capability.id}
            className={cn(
              "flex items-center justify-between p-3 rounded-lg border transition-colors",
              capability.enabled 
                ? "bg-card hover:bg-accent/30" 
                : "bg-muted/30 opacity-60"
            )}
          >
            <div className="flex items-center gap-2">
              {capability.enabled ? (
                <CheckCircle2 className="h-4 w-4 text-emerald-500" />
              ) : (
                <AlertCircle className="h-4 w-4 text-muted-foreground" />
              )}
              <div>
                <p className="text-sm font-medium">{capability.name}</p>
                <p className="text-xs text-muted-foreground">{capability.description}</p>
              </div>
            </div>
            
            {capability.usageToday !== undefined && capability.limit && (
              <div className="text-right">
                <p className="text-xs font-medium">
                  {capability.usageToday}/{capability.limit}
                </p>
                <Progress 
                  value={(capability.usageToday / capability.limit) * 100} 
                  className="h-1 w-12"
                />
              </div>
            )}
          </div>
        ))}
        
        <Button
          variant="outline"
          size="sm"
          className="w-full mt-2"
          onClick={() => context.onAction?.('open_agent_settings', { agentId })}
        >
          <Settings className="h-4 w-4 mr-2" />
          配置 Agent
        </Button>
      </CardContent>
    </Card>
  );
}

// Agent 思考指示器组件
interface AgentThinkingProps {
  props: {
    agentId: string;
    message?: string;
    steps?: Array<{
      id: string;
      label: string;
      status: 'pending' | 'active' | 'completed';
    }>;
  };
  context: RenderContext;
}

export function AgentThinking({ props, context }: AgentThinkingProps) {
  const { agentId, message = '思考中...', steps } = props;
  const agent = AI_AGENTS[agentId] || AI_AGENTS.service;

  return (
    <div className="flex items-start gap-3 p-4 rounded-lg bg-muted/50 border">
      <div className="relative">
        <Avatar className="h-10 w-10">
          <AvatarImage src={agent.avatar} alt={agent.name} />
          <AvatarFallback className={agent.color}>
            {agent.emoji}
          </AvatarFallback>
        </Avatar>
        <span className="absolute -bottom-0.5 -right-0.5 flex h-3 w-3">
          <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-3 w-3 bg-primary"></span>
        </span>
      </div>
      
      <div className="flex-1">
        <div className="flex items-center gap-2 mb-2">
          <span className="text-sm font-medium">{agent.name}</span>
          <Brain className="h-4 w-4 text-primary animate-pulse" />
          <span className="text-xs text-muted-foreground">{message}</span>
        </div>
        
        {steps && steps.length > 0 && (
          <div className="flex items-center gap-1">
            {steps.map((step, index) => (
              <div
                key={step.id}
                className={cn(
                  "h-1.5 flex-1 rounded-full transition-all",
                  step.status === 'completed' && "bg-primary",
                  step.status === 'active' && "bg-primary/50 animate-pulse",
                  step.status === 'pending' && "bg-muted"
                )}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

export default AgentStatus;
