/**
 * Agent 能力卡片组件
 * 展示 AI Agent 的核心能力和当前状态
 */

import { useState } from 'react';
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,
  Shield,
  Clock,
  Activity,
  ChevronRight,
  Settings,
  Sparkles,
  CheckCircle2,
  AlertCircle,
  TrendingUp
} from 'lucide-react';
import type { AIAgent } from '@/types/agents';

export interface AgentCapability {
  id: string;
  name: string;
  description: string;
  enabled: boolean;
  usageToday?: number;
  limit?: number;
}

export interface AgentMetric {
  label: string;
  value: string | number;
  trend?: 'up' | 'down' | 'neutral';
  change?: string;
}

export interface AgentCapabilityCardProps {
  agent: AIAgent;
  status: 'online' | 'busy' | 'offline';
  capabilities: AgentCapability[];
  metrics?: AgentMetric[];
  lastActivity?: string;
  onSettingsClick?: () => void;
  onCapabilityToggle?: (capabilityId: string, enabled: boolean) => void;
  className?: string;
}

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 AgentCapabilityCard({
  agent,
  status,
  capabilities,
  metrics,
  lastActivity,
  onSettingsClick,
  onCapabilityToggle,
  className,
}: AgentCapabilityCardProps) {
  const [showAllCapabilities, setShowAllCapabilities] = useState(false);
  const statusConfig = STATUS_CONFIG[status];
  
  const displayedCapabilities = showAllCapabilities 
    ? capabilities 
    : capabilities.slice(0, 3);

  return (
    <Card className={cn("overflow-hidden", className)}>
      {/* Header with Agent info */}
      <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>
              {/* Status indicator */}
              <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>
          
          {onSettingsClick && (
            <Button variant="ghost" size="icon" onClick={onSettingsClick}>
              <Settings className="h-4 w-4" />
            </Button>
          )}
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        {/* Quick 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>
        )}

        {/* Capabilities */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <h4 className="text-sm font-medium flex items-center gap-1.5">
              <Zap className="h-4 w-4 text-primary" />
              Agent 能力
            </h4>
            <span className="text-xs text-muted-foreground">
              {capabilities.filter(c => c.enabled).length}/{capabilities.length} 已启用
            </span>
          </div>
          
          <div className="space-y-2">
            {displayedCapabilities.map((capability) => (
              <div 
                key={capability.id}
                className={cn(
                  "flex items-center justify-between p-2 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>
            ))}
          </div>
          
          {capabilities.length > 3 && (
            <Button
              variant="ghost"
              size="sm"
              className="w-full mt-2 text-xs"
              onClick={() => setShowAllCapabilities(!showAllCapabilities)}
            >
              {showAllCapabilities ? '收起' : `查看全部 ${capabilities.length} 项能力`}
              <ChevronRight className={cn(
                "h-4 w-4 ml-1 transition-transform",
                showAllCapabilities && "rotate-90"
              )} />
            </Button>
          )}
        </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 状态指示器
 */
export function AgentStatusIndicator({
  agent,
  status,
  className,
}: {
  agent: AIAgent;
  status: 'online' | 'busy' | 'offline';
  className?: string;
}) {
  const statusConfig = STATUS_CONFIG[status];
  
  return (
    <div className={cn("flex items-center gap-2", className)}>
      <div className="relative">
        <Avatar className="h-8 w-8">
          <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">
          {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-3 w-3 border-2 border-background", statusConfig.color)}></span>
        </span>
      </div>
      
      <div>
        <p className="text-sm font-medium leading-none">{agent.name}</p>
        <p className={cn("text-xs", statusConfig.textColor)}>{statusConfig.label}</p>
      </div>
    </div>
  );
}

export default AgentCapabilityCard;
