/**
 * AI 团队中心 (MVP)
 * - Agent 列表卡片：5 个业务 Agent 的状态总览
 * - 全局引擎开关：C 端 Dify/Coze + 流式输出
 * - 未来引擎占位：OpenClaw / Manus 等
 * 配置存 localStorage（管理员浏览器级），后续可升级到数据库表。
 */

import { useState, useEffect } from 'react';
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 { Label } from '@/components/ui/label';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, Settings, Bot, Zap, Cpu, Sparkles, Lock } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { AI_AGENTS } from '@/types/agents';
import { AgentSettingsDialog } from './AgentSettingsDialog';
import { toast } from 'sonner';

interface AgentSettingRow {
  agent_type: string;
  is_active: boolean;
  auto_execute_enabled: boolean;
  max_auto_amount: number;
}

interface GlobalEngineConfig {
  consumerEngine: 'dify' | 'coze';
  consumerStreamEnabled: boolean;
  adminEngine: 'coze' | 'dify';
  adminStreamEnabled: boolean;
}

const STORAGE_KEY = 'ai_engine_config_v1';

const DEFAULT_CONFIG: GlobalEngineConfig = {
  consumerEngine: 'dify',
  consumerStreamEnabled: true,
  adminEngine: 'coze',
  adminStreamEnabled: true,
};

function loadConfig(): GlobalEngineConfig {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) return { ...DEFAULT_CONFIG, ...JSON.parse(raw) };
  } catch (e) {
    console.warn('[AITeamCenter] Failed to parse config:', e);
  }
  return DEFAULT_CONFIG;
}

function saveConfig(config: GlobalEngineConfig) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(config));
}

const FUTURE_ENGINES = [
  {
    id: 'openclaw',
    name: 'OpenClaw',
    description: '新一代自主任务 Agent，支持复杂工作流编排',
    tag: '即将接入',
    icon: '🦾',
  },
  {
    id: 'manus',
    name: 'Manus',
    description: '通用任务执行 Agent，可调用浏览器和工具链',
    tag: '评估中',
    icon: '🤖',
  },
  {
    id: 'autogen',
    name: 'AutoGen',
    description: 'Microsoft 多 Agent 协作编排框架',
    tag: '规划中',
    icon: '🔀',
  },
];

export function AITeamCenter() {
  const [agents, setAgents] = useState<AgentSettingRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [config, setConfig] = useState<GlobalEngineConfig>(DEFAULT_CONFIG);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [selectedAgentType, setSelectedAgentType] = useState<string | undefined>();

  useEffect(() => {
    setConfig(loadConfig());
    loadAgents();
  }, []);

  const loadAgents = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('agent_settings')
        .select('agent_type, is_active, auto_execute_enabled, max_auto_amount')
        .order('agent_type');
      if (error) throw error;
      setAgents((data || []) as AgentSettingRow[]);
    } catch (e) {
      console.error('Load agents failed:', e);
      toast.error('加载 Agent 状态失败');
    } finally {
      setLoading(false);
    }
  };

  const updateConfig = (patch: Partial<GlobalEngineConfig>) => {
    const next = { ...config, ...patch };
    setConfig(next);
    saveConfig(next);
    toast.success('配置已保存');
  };

  const openAgentSettings = (agentType: string) => {
    setSelectedAgentType(agentType);
    setSettingsOpen(true);
  };

  const activeCount = agents.filter((a) => a.is_active).length;

  return (
    <div className="space-y-4 h-full overflow-auto pr-1">
      {/* 顶部状态栏 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex items-center justify-between flex-wrap gap-3">
            <div className="flex items-center gap-3">
              <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                <Bot className="h-5 w-5 text-primary" />
              </div>
              <div>
                <h3 className="font-semibold flex items-center gap-2">
                  AI 团队中心
                  <Badge variant="secondary">MVP</Badge>
                </h3>
                <p className="text-xs text-muted-foreground">
                  {activeCount}/{agents.length} 在线 · 引擎 C 端 {config.consumerEngine.toUpperCase()} · B 端 {config.adminEngine.toUpperCase()}
                </p>
              </div>
            </div>
            <Button variant="outline" size="sm" onClick={loadAgents} disabled={loading}>
              {loading && <Loader2 className="h-3 w-3 mr-1.5 animate-spin" />}
              刷新
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 业务 Agent 列表 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            业务 Agent
          </CardTitle>
          <CardDescription>5 位 AI 助理，分别负责不同业务域</CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="py-8 text-center">
              <Loader2 className="h-5 w-5 animate-spin text-muted-foreground mx-auto" />
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
              {Object.entries(AI_AGENTS).map(([key, agent]) => {
                const setting = agents.find((a) => a.agent_type === key);
                const isActive = setting?.is_active ?? true;
                const autoExec = setting?.auto_execute_enabled ?? false;
                const maxAmount = setting?.max_auto_amount ?? 0;

                return (
                  <div
                    key={key}
                    className="border rounded-lg p-3 hover:border-primary/50 transition-colors group"
                  >
                    <div className="flex items-start justify-between gap-2 mb-2">
                      <div className="flex items-center gap-2 min-w-0">
                        <Avatar className="h-9 w-9 flex-shrink-0">
                          <AvatarImage src={agent.avatar} alt={agent.name} />
                          <AvatarFallback>{agent.emoji}</AvatarFallback>
                        </Avatar>
                        <div className="min-w-0">
                          <div className="flex items-center gap-1.5">
                            <span className="font-medium truncate">{agent.name}</span>
                            <span
                              className={`h-1.5 w-1.5 rounded-full flex-shrink-0 ${
                                isActive ? 'bg-emerald-500' : 'bg-muted-foreground/40'
                              }`}
                            />
                          </div>
                          <p className="text-xs text-muted-foreground truncate">{agent.role}</p>
                        </div>
                      </div>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
                        onClick={() => openAgentSettings(key)}
                      >
                        <Settings className="h-3.5 w-3.5" />
                      </Button>
                    </div>

                    <div className="flex items-center gap-1.5 flex-wrap">
                      <Badge variant={isActive ? 'default' : 'secondary'} className="text-xs h-5">
                        {isActive ? '运行中' : '已暂停'}
                      </Badge>
                      {autoExec && (
                        <Badge variant="outline" className="text-xs h-5 gap-1">
                          <Zap className="h-2.5 w-2.5" />
                          自动 ¥{maxAmount.toLocaleString()}
                        </Badge>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 全局引擎配置 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <Cpu className="h-4 w-4 text-primary" />
            AI 引擎配置
          </CardTitle>
          <CardDescription>全局引擎选择与流式输出开关（影响所有用户）</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* C 端配置 */}
          <div className="border rounded-lg p-4 space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <Label className="text-sm font-medium">C 端消费者助手</Label>
                <p className="text-xs text-muted-foreground">商城聊天页面使用的 AI 引擎</p>
              </div>
              <Badge variant="outline" className="text-xs">面向用户</Badge>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">引擎</Label>
                <Select
                  value={config.consumerEngine}
                  onValueChange={(v) => updateConfig({ consumerEngine: v as 'dify' | 'coze' })}
                >
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="dify">Dify（推荐）</SelectItem>
                    <SelectItem value="coze">Coze</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="flex items-center justify-between border rounded-md px-3 h-9 mt-auto">
                <Label htmlFor="c-stream" className="text-sm cursor-pointer">流式输出</Label>
                <Switch
                  id="c-stream"
                  checked={config.consumerStreamEnabled}
                  onCheckedChange={(v) => updateConfig({ consumerStreamEnabled: v })}
                />
              </div>
            </div>
          </div>

          {/* B 端配置 */}
          <div className="border rounded-lg p-4 space-y-3">
            <div className="flex items-center justify-between">
              <div>
                <Label className="text-sm font-medium">B 端管理后台助手</Label>
                <p className="text-xs text-muted-foreground">管理员 AI 副驾使用的引擎</p>
              </div>
              <Badge variant="outline" className="text-xs">面向员工</Badge>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label className="text-xs text-muted-foreground">引擎</Label>
                <Select
                  value={config.adminEngine}
                  onValueChange={(v) => updateConfig({ adminEngine: v as 'coze' | 'dify' })}
                >
                  <SelectTrigger className="h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="coze">Coze（推荐）</SelectItem>
                    <SelectItem value="dify">Dify</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="flex items-center justify-between border rounded-md px-3 h-9 mt-auto">
                <Label htmlFor="b-stream" className="text-sm cursor-pointer">流式输出</Label>
                <Switch
                  id="b-stream"
                  checked={config.adminStreamEnabled}
                  onCheckedChange={(v) => updateConfig({ adminStreamEnabled: v })}
                />
              </div>
            </div>
          </div>

          <p className="text-xs text-muted-foreground flex items-center gap-1.5">
            <Lock className="h-3 w-3" />
            配置当前仅在本浏览器生效，多端同步需后续升级到数据库。
          </p>
        </CardContent>
      </Card>

      {/* 未来引擎市场 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base flex items-center gap-2">
            <Sparkles className="h-4 w-4 text-primary" />
            新一代 Agent 引擎市场
          </CardTitle>
          <CardDescription>预留接入位，待官方稳定后陆续开放</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            {FUTURE_ENGINES.map((engine) => (
              <div
                key={engine.id}
                className="border border-dashed rounded-lg p-4 bg-muted/30 hover:bg-muted/50 transition-colors"
              >
                <div className="flex items-start justify-between mb-2">
                  <div className="text-2xl">{engine.icon}</div>
                  <Badge variant="secondary" className="text-xs">
                    {engine.tag}
                  </Badge>
                </div>
                <h4 className="font-medium mb-1">{engine.name}</h4>
                <p className="text-xs text-muted-foreground line-clamp-2">{engine.description}</p>
                <Button variant="ghost" size="sm" className="w-full mt-3 h-8 text-xs" disabled>
                  敬请期待
                </Button>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <AgentSettingsDialog
        open={settingsOpen}
        onOpenChange={(o) => {
          setSettingsOpen(o);
          if (!o) loadAgents();
        }}
        agentType={selectedAgentType}
      />
    </div>
  );
}

export default AITeamCenter;
