/**
 * Agent 配置卡片 GenUI 组件
 * 用于AI通过自然语言展示和配置Agent设置
 */

import { cn } from '@/lib/utils';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Progress } from '@/components/ui/progress';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';
import {
  Bot,
  Zap,
  Shield,
  Bell,
  Target,
  Settings,
  CheckCircle2,
  AlertTriangle,
  DollarSign,
  FileCheck,
  Volume2,
  VolumeX,
  Edit3,
  Power
} from 'lucide-react';
import { AI_AGENTS } from '@/types/agents';
import type { RenderContext } from '../types';

// Agent 设置数据结构
export interface AgentSettingsData {
  agentType: string;
  isActive: boolean;
  autoExecuteEnabled: boolean;
  maxAutoAmount: number;
  responseStyle: string;
  tone: string;
  requiresApprovalTypes: string[];
  notifyOnInsights: boolean;
  notifyOnApprovals: boolean;
  notifyOnErrors: boolean;
  monthlyGoals?: Record<string, any>;
}

// Agent 配置卡片 Props
interface AgentSettingsCardProps {
  props: {
    data: AgentSettingsData;
    showActions?: boolean;
    compact?: boolean;
  };
  context: RenderContext;
}

// 审批类型标签映射
const APPROVAL_TYPE_LABELS: Record<string, string> = {
  refund: '退款审批',
  price_change: '价格调整',
  campaign_create: '活动创建',
  campaign_update: '活动修改',
  product_delete: '商品删除',
  order_cancel: '订单取消',
  user_block: '用户封禁',
  aftersales_approve: '售后审批',
  goal_create: '目标创建',
};

// 响应风格标签
const STYLE_LABELS: Record<string, string> = {
  professional: '专业正式',
  friendly: '亲切友好',
  concise: '简洁高效',
  detailed: '详细全面',
};

// 语气标签
const TONE_LABELS: Record<string, string> = {
  formal: '正式',
  casual: '随和',
  enthusiastic: '热情',
  calm: '沉稳',
};

export function AgentSettingsCard({ props, context }: AgentSettingsCardProps) {
  const { data, showActions = true, compact = false } = props;
  const agent = AI_AGENTS[data.agentType] || AI_AGENTS.manager;

  const handleToggleAutoExecute = () => {
    context.onAction?.('set_agent_auto_execute', {
      agentType: data.agentType,
      enabled: !data.autoExecuteEnabled,
    });
  };

  const handleToggleNotification = (type: 'insights' | 'approvals' | 'errors') => {
    const notificationParams: Record<string, boolean> = {};
    notificationParams[`notifyOn${type.charAt(0).toUpperCase() + type.slice(1)}`] = 
      type === 'insights' ? !data.notifyOnInsights :
      type === 'approvals' ? !data.notifyOnApprovals :
      !data.notifyOnErrors;
    
    context.onAction?.('set_agent_notifications', {
      agentType: data.agentType,
      ...notificationParams,
    });
  };

  const handleEditSettings = () => {
    context.onAction?.('open_agent_settings', { agentType: data.agentType });
  };

  if (compact) {
    return (
      <Card className="overflow-hidden">
        <CardContent className="p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Avatar className="h-10 w-10">
                <AvatarImage src={agent.avatar} alt={agent.name} />
                <AvatarFallback className={agent.color}>
                  {agent.emoji}
                </AvatarFallback>
              </Avatar>
              <div>
                <h4 className="font-medium">{agent.name}</h4>
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Badge variant={data.isActive ? 'default' : 'secondary'} className="text-xs">
                    {data.isActive ? '运行中' : '已暂停'}
                  </Badge>
                  {data.autoExecuteEnabled && (
                    <Badge variant="outline" className="text-xs gap-1">
                      <Zap className="h-3 w-3" />
                      自动
                    </Badge>
                  )}
                </div>
              </div>
            </div>
            
            {showActions && (
              <Button variant="ghost" size="icon" onClick={handleEditSettings}>
                <Settings className="h-4 w-4" />
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="overflow-hidden">
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-3">
            <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>
            <div>
              <CardTitle className="text-lg flex items-center gap-2">
                {agent.name}
                <Badge variant={data.isActive ? 'default' : 'secondary'}>
                  {data.isActive ? '运行中' : '已暂停'}
                </Badge>
              </CardTitle>
              <CardDescription>{agent.role}</CardDescription>
            </div>
          </div>
          
          {showActions && (
            <Button variant="outline" size="sm" onClick={handleEditSettings}>
              <Edit3 className="h-4 w-4 mr-1.5" />
              编辑配置
            </Button>
          )}
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        {/* 自动执行设置 */}
        <div className="rounded-lg border p-4 space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Zap className="h-4 w-4 text-amber-500" />
              <span className="font-medium">自动执行</span>
            </div>
            <div className="flex items-center gap-3">
              <Badge variant="outline" className="gap-1">
                <DollarSign className="h-3 w-3" />
                限额 ¥{data.maxAutoAmount.toLocaleString()}
              </Badge>
              {showActions ? (
                <Switch 
                  checked={data.autoExecuteEnabled} 
                  onCheckedChange={handleToggleAutoExecute}
                />
              ) : (
                <Badge variant={data.autoExecuteEnabled ? 'default' : 'secondary'}>
                  {data.autoExecuteEnabled ? '已开启' : '已关闭'}
                </Badge>
              )}
            </div>
          </div>
          
          {data.autoExecuteEnabled && (
            <p className="text-sm text-muted-foreground">
              低于 ¥{data.maxAutoAmount.toLocaleString()} 的操作将自动执行，无需人工审批
            </p>
          )}
        </div>

        {/* 审批类型 */}
        <div className="rounded-lg border p-4 space-y-3">
          <div className="flex items-center gap-2">
            <Shield className="h-4 w-4 text-blue-500" />
            <span className="font-medium">需人工审批</span>
            <Badge variant="secondary" className="ml-auto">
              {data.requiresApprovalTypes.length} 项
            </Badge>
          </div>
          
          <div className="flex flex-wrap gap-1.5">
            {data.requiresApprovalTypes.length > 0 ? (
              data.requiresApprovalTypes.map((type) => (
                <Badge key={type} variant="outline" className="text-xs">
                  {APPROVAL_TYPE_LABELS[type] || type}
                </Badge>
              ))
            ) : (
              <span className="text-sm text-muted-foreground">无需人工审批</span>
            )}
          </div>
        </div>

        {/* 通知设置 */}
        <div className="rounded-lg border p-4 space-y-3">
          <div className="flex items-center gap-2">
            <Bell className="h-4 w-4 text-purple-500" />
            <span className="font-medium">通知设置</span>
          </div>
          
          <div className="grid grid-cols-3 gap-2">
            <div 
              className={cn(
                "flex flex-col items-center gap-1 p-2 rounded-lg text-center cursor-pointer transition-colors",
                data.notifyOnInsights ? "bg-primary/10" : "bg-muted/50"
              )}
              onClick={() => showActions && handleToggleNotification('insights')}
            >
              {data.notifyOnInsights ? (
                <CheckCircle2 className="h-4 w-4 text-primary" />
              ) : (
                <VolumeX className="h-4 w-4 text-muted-foreground" />
              )}
              <span className="text-xs">洞察通知</span>
            </div>
            
            <div 
              className={cn(
                "flex flex-col items-center gap-1 p-2 rounded-lg text-center cursor-pointer transition-colors",
                data.notifyOnApprovals ? "bg-primary/10" : "bg-muted/50"
              )}
              onClick={() => showActions && handleToggleNotification('approvals')}
            >
              {data.notifyOnApprovals ? (
                <CheckCircle2 className="h-4 w-4 text-primary" />
              ) : (
                <VolumeX className="h-4 w-4 text-muted-foreground" />
              )}
              <span className="text-xs">审批通知</span>
            </div>
            
            <div 
              className={cn(
                "flex flex-col items-center gap-1 p-2 rounded-lg text-center cursor-pointer transition-colors",
                data.notifyOnErrors ? "bg-primary/10" : "bg-muted/50"
              )}
              onClick={() => showActions && handleToggleNotification('errors')}
            >
              {data.notifyOnErrors ? (
                <CheckCircle2 className="h-4 w-4 text-primary" />
              ) : (
                <VolumeX className="h-4 w-4 text-muted-foreground" />
              )}
              <span className="text-xs">错误通知</span>
            </div>
          </div>
        </div>

        {/* 响应风格 */}
        <div className="flex items-center gap-4 text-sm">
          <div className="flex items-center gap-2">
            <span className="text-muted-foreground">响应风格:</span>
            <Badge variant="outline">{STYLE_LABELS[data.responseStyle] || data.responseStyle}</Badge>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-muted-foreground">语气:</span>
            <Badge variant="outline">{TONE_LABELS[data.tone] || data.tone}</Badge>
          </div>
        </div>

        {/* 操作按钮 */}
        {showActions && (
          <>
            <Separator />
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                className="flex-1"
                onClick={() => context.onAction?.('update_agent', {
                  agentType: data.agentType,
                  isActive: !data.isActive,
                })}
              >
                <Power className="h-4 w-4 mr-1.5" />
                {data.isActive ? '暂停Agent' : '启用Agent'}
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="flex-1"
                onClick={() => context.onAction?.('query_agent', {
                  agentType: data.agentType,
                })}
              >
                <FileCheck className="h-4 w-4 mr-1.5" />
                刷新配置
              </Button>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
}

// Agent 配置列表组件
interface AgentSettingsListProps {
  props: {
    agents: AgentSettingsData[];
    title?: string;
  };
  context: RenderContext;
}

export function AgentSettingsList({ props, context }: AgentSettingsListProps) {
  const { agents, title = 'Agent 配置概览' } = props;

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold flex items-center gap-2">
          <Bot className="h-5 w-5 text-primary" />
          {title}
        </h3>
        <Badge variant="secondary">
          {agents.filter(a => a.isActive).length}/{agents.length} 运行中
        </Badge>
      </div>
      
      <div className="grid gap-3">
        {agents.map((agent) => (
          <AgentSettingsCard
            key={agent.agentType}
            props={{ data: agent, compact: true, showActions: true }}
            context={context}
          />
        ))}
      </div>
    </div>
  );
}

export default AgentSettingsCard;
