import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { ArrowLeft, Bot, Database, CheckSquare, Square } from 'lucide-react'
import toast from 'react-hot-toast'
import { agentsApi } from '../api/agents'
import { providersApi } from '../api/providers'
import { knowledgeApi } from '../api/knowledge'
import { Card, PageHeader, Button, Input, Textarea, Select, Tabs } from '../components/ui'

const SYSTEM_PROMPT_TEMPLATES = [
  { label: '通用助手', prompt: '你是一个智能助手，能够回答各种问题，提供清晰准确的信息和帮助。' },
  { label: '文档问答', prompt: '你是一个文档问答助手。根据用户提供的内容，准确地回答问题，引用相关段落。如果问题超出文档范围，请明确说明。' },
  { label: '代码助手', prompt: '你是一个编程助手，擅长代码审查、调试和技术问题解答。回答时提供清晰的代码示例。' },
  { label: '数据分析', prompt: '你是一个数据分析助手，帮助用户理解数据、生成洞察和撰写分析报告。' },
]

const MODEL_MAP: Record<string, string[]> = {
  'claude-code': ['sonnet', 'opus', 'haiku'],
  anthropic: ['claude-sonnet-4-6', 'claude-opus-4-7', 'claude-haiku-4-5-20251001'],
  dashscope: ['qwen3-max-2026-01-23', 'qwen-max', 'qwen-plus', 'qwen-turbo'],
  deepseek: ['deepseek-chat', 'deepseek-reasoner'],
  openai: ['gpt-4o', 'gpt-4o-mini'],
  zhipu: ['glm-4-plus', 'glm-4-flash'],
  moonshot: ['moonshot-v1-8k', 'moonshot-v1-32k'],
  ollama: ['qwen2.5:7b', 'llama3.2:3b', 'mistral:7b'],
}

const tabs = [
  { id: 'basic', label: '基本设置' },
  { id: 'model', label: '模型配置' },
  { id: 'prompt', label: '系统提示词' },
  { id: 'kb', label: '知识库' },
]

export default function AgentCreate() {
  const navigate = useNavigate()
  const qc = useQueryClient()

  const [activeTab, setActiveTab] = useState('basic')
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [tags, setTags] = useState('')
  const [provider, setProvider] = useState('')
  const [modelName, setModelName] = useState('')
  const [temperature, setTemperature] = useState('0.7')
  const [maxTokens, setMaxTokens] = useState('4096')
  const [systemPrompt, setSystemPrompt] = useState(SYSTEM_PROMPT_TEMPLATES[0].prompt)
  const [selectedKBs, setSelectedKBs] = useState<string[]>([])
  const [kbSearchMode, setKbSearchMode] = useState('bm25')
  // 任务型(ReAct)+ 进度纪律:勾选则建可多步读写文件的 react 智能体并开 PROGRESS.md 纪律;
  // 不勾为纯对话问答型(conversation)。
  const [taskMode, setTaskMode] = useState(false)

  const { data: providerData } = useQuery({
    queryKey: ['providers'],
    queryFn: providersApi.list,
  })

  const configuredProviders = providerData?.providers?.filter(p => p.configured) ?? []

  const { data: kbData } = useQuery({
    queryKey: ['knowledge-bases'],
    queryFn: knowledgeApi.list,
  })
  const allKBs = kbData?.items ?? []

  function handleProviderChange(p: string) {
    setProvider(p)
    const models = MODEL_MAP[p] ?? []
    setModelName(models[0] ?? '')
  }

  const mutation = useMutation({
    mutationFn: () =>
      agentsApi.create({
        name,
        description,
        config: {
          agentId: name.toLowerCase().replace(/\s+/g, '-'),
          name,
          description,
          type: taskMode ? 'react' : 'conversation',
          systemPrompt,
          model: {
            provider,
            name: modelName,
            temperature: parseFloat(temperature),
            maxTokens: parseInt(maxTokens, 10),
          },
          // 任务型:给默认 react 配置 + 开进度纪律(平台自动配内置读写/跑命令工具)。
          ...(taskMode ? { react: { maxSteps: 20, progressDiscipline: true } } : {}),
        },
        tags: tags
          .split(',')
          .map(t => t.trim())
          .filter(Boolean),
        kb_ids: selectedKBs,
        kb_search_mode: kbSearchMode,
      }),
    onSuccess: data => {
      qc.invalidateQueries({ queryKey: ['agents'] })
      toast.success('智能体创建成功！')
      navigate(`/chat/${data.agent_id}`)
    },
    onError: (e: Error) => toast.error(`创建失败：${e.message}`),
  })

  const canSave = name.trim() && provider && modelName

  return (
    <div className="p-8 max-w-2xl mx-auto">
      <button
        onClick={() => navigate('/agents')}
        className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-900 mb-6 transition-colors"
      >
        <ArrowLeft size={16} />
        返回列表
      </button>

      <PageHeader
        title="新建智能体"
        description="选择模型和角色，几秒钟即可创建完成"
      />

      <Card>
        <Tabs tabs={tabs} active={activeTab} onChange={setActiveTab} />

        {/* ── 基本设置 ── */}
        {activeTab === 'basic' && (
          <div className="space-y-5">
            <Input
              label="名称 *"
              placeholder="例如：客服助理、法律顾问…"
              value={name}
              onChange={e => setName(e.target.value)}
              maxLength={64}
            />
            <Textarea
              label="描述"
              placeholder="简短描述这个智能体的用途"
              value={description}
              onChange={e => setDescription(e.target.value)}
              rows={2}
            />
            <Input
              label="标签"
              placeholder="用英文逗号分隔，例如：qa, finance"
              value={tags}
              onChange={e => setTags(e.target.value)}
              hint="标签便于筛选和分类"
            />
            <label className="flex items-start gap-2 cursor-pointer rounded-lg border border-gray-200 p-3 hover:bg-gray-50">
              <input type="checkbox" className="mt-0.5" checked={taskMode}
                     onChange={e => setTaskMode(e.target.checked)} />
              <span className="text-sm">
                <span className="font-medium text-gray-800">任务型智能体（可读写文件、多步执行）</span>
                <span className="block text-xs text-gray-500 mt-0.5">
                  勾选则创建 ReAct 智能体，可读写文件/跑命令，并自动维护工作目录里的
                  PROGRESS.md 进度清单（逐项打勾、不重做、不做完不收尾），防多步任务"乱跳/重做"。
                  不勾则为纯对话问答型。创建后可在「编辑 → 行为」里再调整。
                </span>
              </span>
            </label>
            <Button onClick={() => setActiveTab('model')} className="w-full" disabled={!name.trim()}>
              下一步：模型配置
            </Button>
          </div>
        )}

        {/* ── 模型配置 ── */}
        {activeTab === 'model' && (
          <div className="space-y-5">
            {configuredProviders.length === 0 ? (
              <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-4 text-sm text-yellow-800">
                暂无可用的模型提供商。请先在{' '}
                <button
                  onClick={() => navigate('/settings/providers')}
                  className="underline font-medium"
                >
                  模型提供商
                </button>{' '}
                页面配置 API Key。
              </div>
            ) : (
              <>
                <Select
                  label="提供商 *"
                  value={provider}
                  onChange={e => handleProviderChange(e.target.value)}
                  options={[
                    { value: '', label: '请选择提供商' },
                    ...configuredProviders.map(p => ({ value: p.id, label: p.name })),
                  ]}
                />
                {provider && (
                  <Select
                    label="模型 *"
                    value={modelName}
                    onChange={e => setModelName(e.target.value)}
                    options={(MODEL_MAP[provider] ?? []).map(m => ({ value: m, label: m }))}
                  />
                )}
              </>
            )}

            <div className="grid grid-cols-2 gap-4">
              <Input
                label="Temperature"
                type="number"
                min="0"
                max="1"
                step="0.1"
                value={temperature}
                onChange={e => setTemperature(e.target.value)}
                hint="0 = 确定性，1 = 创意性"
              />
              <Input
                label="最大 Token 数"
                type="number"
                min="256"
                max="32768"
                step="256"
                value={maxTokens}
                onChange={e => setMaxTokens(e.target.value)}
              />
            </div>

            <Button onClick={() => setActiveTab('prompt')} className="w-full" disabled={!provider || !modelName}>
              下一步：提示词
            </Button>
          </div>
        )}

        {/* ── 系统提示词 ── */}
        {activeTab === 'prompt' && (
          <div className="space-y-4">
            <div className="flex gap-2 flex-wrap">
              {SYSTEM_PROMPT_TEMPLATES.map(t => (
                <button
                  key={t.label}
                  onClick={() => setSystemPrompt(t.prompt)}
                  className="px-3 py-1 text-xs border border-gray-200 rounded-full hover:border-indigo-400 hover:text-indigo-600 transition-colors"
                >
                  {t.label}
                </button>
              ))}
            </div>

            <Textarea
              label="系统提示词"
              value={systemPrompt}
              onChange={e => setSystemPrompt(e.target.value)}
              rows={8}
              hint={`${systemPrompt.length} 字符`}
            />

            <Button
              onClick={() => mutation.mutate()}
              loading={mutation.isPending}
              size="lg"
              className="w-full"
              disabled={!canSave}
              icon={<Bot size={16} />}
            >
              {canSave ? '创建智能体并开始对话' : '请先完善必填项'}
            </Button>
          </div>
        )}

        {/* ── 知识库 ── */}
        {activeTab === 'kb' && (
          <div className="space-y-5">
            <p className="text-xs text-gray-500">
              选择知识库后，每次对话前会自动检索相关内容并注入到提示词中（RAG 增强）。
            </p>

            {/* Search mode */}
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">检索模式</label>
              <select
                value={kbSearchMode}
                onChange={e => setKbSearchMode(e.target.value)}
                className="rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
              >
                <option value="bm25">BM25 关键词检索（推荐）</option>
                <option value="pageindex">PageIndex 页面级检索</option>
              </select>
            </div>

            {/* KB multi-select */}
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-2">
                可用知识库
                {selectedKBs.length > 0 && (
                  <span className="ml-2 text-indigo-600">（已选 {selectedKBs.length} 个）</span>
                )}
              </label>
              {allKBs.length === 0 ? (
                <div className="rounded-lg border border-dashed border-gray-200 p-6 text-center text-sm text-gray-400">
                  <Database size={24} className="mx-auto mb-2 opacity-40" />
                  暂无知识库，请先在知识库页面创建
                </div>
              ) : (
                <div className="space-y-2">
                  {allKBs.map(kb => {
                    const checked = selectedKBs.includes(kb.id)
                    return (
                      <button
                        key={kb.id}
                        type="button"
                        onClick={() => setSelectedKBs(prev =>
                          checked ? prev.filter(id => id !== kb.id) : [...prev, kb.id]
                        )}
                        className={`w-full flex items-center gap-3 rounded-lg border p-3 text-left transition-colors ${
                          checked
                            ? 'border-indigo-300 bg-indigo-50'
                            : 'border-gray-200 bg-white hover:border-gray-300'
                        }`}
                      >
                        {checked
                          ? <CheckSquare size={15} className="text-indigo-600 shrink-0" />
                          : <Square size={15} className="text-gray-300 shrink-0" />}
                        <div className="min-w-0">
                          <p className="text-sm font-medium text-gray-800 truncate">{kb.name}</p>
                          {kb.description && (
                            <p className="text-xs text-gray-500 truncate">{kb.description}</p>
                          )}
                        </div>
                        <div className="ml-auto flex gap-1.5 shrink-0">
                          {kb.index_status?.bm25?.exists && (
                            <span className="text-xs bg-blue-100 text-blue-600 px-1.5 py-0.5 rounded">BM25</span>
                          )}
                          {(kb.index_status as any)?.pageindex?.exists && (
                            <span className="text-xs bg-orange-100 text-orange-600 px-1.5 py-0.5 rounded">PageIndex</span>
                          )}
                          {kb.index_status?.wiki?.exists && (
                            <span className="text-xs bg-green-100 text-green-600 px-1.5 py-0.5 rounded">Wiki</span>
                          )}
                        </div>
                      </button>
                    )
                  })}
                </div>
              )}
            </div>

            <Button
              onClick={() => mutation.mutate()}
              loading={mutation.isPending}
              size="lg"
              className="w-full"
              disabled={!canSave}
              icon={<Bot size={16} />}
            >
              {canSave ? '创建智能体' : '请先完善必填项（名称/模型）'}
            </Button>
          </div>
        )}
      </Card>
    </div>
  )
}
