import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { useQuery, useMutation } from '@tanstack/react-query'
import { ArrowLeft, Bot, Zap, Database, CheckCircle2, X, FolderOpen } from 'lucide-react'
import toast from 'react-hot-toast'
import { templatesApi, type TemplateSummary } from '../api/templates'
import { agentsApi } from '../api/agents'
import { Button, Input, Textarea, Card, PageHeader, Spinner, Tabs } from '../components/ui'
import { clsx } from '../lib/clsx'
import DirPickerModal from '../components/DirPickerModal'

// ── Provider badge ────────────────────────────────────────

const PROVIDER_COLORS: Record<string, string> = {
  'claude-code': 'bg-purple-100 text-purple-700',
  anthropic:     'bg-purple-100 text-purple-700',
  dashscope:     'bg-blue-100 text-blue-700',
  deepseek:      'bg-cyan-100 text-cyan-700',
  openai:        'bg-green-100 text-green-700',
  ollama:        'bg-gray-100 text-gray-700',
}

function ProviderBadge({ provider }: { provider: string }) {
  const cls = PROVIDER_COLORS[provider] ?? 'bg-gray-100 text-gray-600'
  return (
    <span className={clsx('text-xs px-2 py-0.5 rounded-full font-medium', cls)}>
      {provider || '未知'}
    </span>
  )
}

// ── Template card ─────────────────────────────────────────

function TemplateCard({
  t,
  selected,
  onClick,
}: {
  t: TemplateSummary
  selected: boolean
  onClick: () => void
}) {
  return (
    <button
      onClick={onClick}
      className={clsx(
        'w-full text-left rounded-xl border p-4 transition-all',
        selected
          ? 'border-indigo-500 bg-indigo-50 ring-2 ring-indigo-400'
          : 'border-gray-200 bg-white hover:border-indigo-300 hover:shadow-sm',
      )}
    >
      <div className="flex items-start justify-between gap-2 mb-2">
        <div className="flex items-center gap-2 min-w-0">
          <div className="w-7 h-7 rounded-lg bg-indigo-100 flex items-center justify-center shrink-0">
            <Bot size={14} className="text-indigo-600" />
          </div>
          <span className="text-sm font-semibold text-gray-900 truncate">{t.name}</span>
        </div>
        {selected && <CheckCircle2 size={16} className="text-indigo-600 shrink-0" />}
      </div>

      <p className="text-xs text-gray-500 line-clamp-2 mb-3 min-h-[2.5rem]">
        {t.description || '暂无描述'}
      </p>

      <div className="flex flex-wrap items-center gap-1.5">
        <ProviderBadge provider={t.provider} />
        {t.model && (
          <span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">
            {t.model}
          </span>
        )}
        {t.has_tools && (
          <span className="text-xs bg-amber-50 text-amber-700 px-2 py-0.5 rounded-full flex items-center gap-1">
            <Zap size={9} />工具
          </span>
        )}
        {t.has_memory && (
          <span className="text-xs bg-teal-50 text-teal-700 px-2 py-0.5 rounded-full flex items-center gap-1">
            <Database size={9} />记忆
          </span>
        )}
      </div>
    </button>
  )
}

// ── Tools tag editor ──────────────────────────────────────

function ToolTagEditor({
  tools,
  onChange,
}: {
  tools: string[]
  onChange: (tools: string[]) => void
}) {
  const [input, setInput] = useState('')
  const inputRef = useRef<HTMLInputElement>(null)

  function add() {
    const v = input.trim()
    if (v && !tools.includes(v)) onChange([...tools, v])
    setInput('')
    inputRef.current?.focus()
  }

  function remove(t: string) {
    onChange(tools.filter(x => x !== t))
  }

  return (
    <div>
      <div className="flex flex-wrap gap-1.5 mb-2 min-h-[2rem]">
        {tools.map(t => (
          <span
            key={t}
            className="inline-flex items-center gap-1 text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded-full"
          >
            {t}
            <button
              type="button"
              onClick={() => remove(t)}
              className="text-gray-400 hover:text-red-500 transition-colors"
            >
              <X size={10} />
            </button>
          </span>
        ))}
      </div>
      <div className="flex gap-2">
        <input
          ref={inputRef}
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && (e.preventDefault(), add())}
          placeholder="输入工具名，回车添加"
          className="flex-1 rounded-lg border border-gray-300 px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
        />
        <button
          type="button"
          onClick={add}
          disabled={!input.trim()}
          className="px-3 py-1.5 rounded-lg bg-gray-100 text-gray-600 text-sm hover:bg-gray-200 disabled:opacity-40 transition-colors"
        >
          添加
        </button>
      </div>
    </div>
  )
}

// ── MODEL_MAP ─────────────────────────────────────────────

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', 'gpt-4-turbo'],
  ollama: ['qwen2.5:7b', 'qwen2.5:32b', 'llama3.2:3b', 'mistral:7b'],
}

const TABS = [
  { id: 'basic',    label: '基本设置' },
  { id: 'model',    label: '模型配置' },
  { id: 'behavior', label: '行为配置' },
  { id: 'memory',   label: '记忆 & 运行时' },
  { id: 'tools',    label: '工具列表' },
  { id: 'prompt',   label: '系统提示词' },
]

// ── Main page ─────────────────────────────────────────────

export default function AgentImport() {
  const navigate = useNavigate()

  const [selectedId, setSelectedId]   = useState<string | null>(null)
  const [tab, setTab]                 = useState('basic')

  // basic
  const [name, setName]               = useState('')
  const [description, setDescription] = useState('')
  const [agentType, setAgentType]     = useState('react')

  // model
  const [provider, setProvider]       = useState('')
  const [modelName, setModelName]     = useState('')
  const [temperature, setTemperature] = useState('0.7')
  const [maxTokens, setMaxTokens]     = useState('4096')
  const [baseUrl, setBaseUrl]         = useState('')

  // behavior (react)
  const [reactMaxSteps, setReactMaxSteps]   = useState('20')
  const [toolTimeout, setToolTimeout]       = useState('60')
  const [thinkTimeout, setThinkTimeout]     = useState('120')

  // memory & runtime
  const [memoryEnabled, setMemoryEnabled]   = useState(false)
  const [memorySize, setMemorySize]         = useState('20')
  const [memoryTtl, setMemoryTtl]           = useState('3600')
  const [runtimeEngine, setRuntimeEngine]   = useState('cek')
  const [costBudget, setCostBudget]         = useState('0.5')

  // tools
  const [localTools, setLocalTools]         = useState<string[]>([])

  // prompt
  const [systemPrompt, setSystemPrompt]     = useState('')

  // 3-directory config
  const [sourceDir, setSourceDir]   = useState('')
  const [workDir, setWorkDir]       = useState('')
  const [runDir, setRunDir]         = useState('')
  const [dirPickerFor, setDirPickerFor] = useState<'work' | 'source' | 'run' | null>(null)

  const { data: listData, isLoading } = useQuery({
    queryKey: ['templates'],
    queryFn: templatesApi.list,
    retry: false,
  })

  const { data: detailData, isFetching: loadingDetail } = useQuery({
    queryKey: ['template', selectedId],
    queryFn: () => templatesApi.get(selectedId!),
    enabled: !!selectedId,
    retry: false,
  })

  useEffect(() => {
    if (!detailData) return
    const cfg  = detailData.template as Record<string, unknown>
    const m    = (cfg.model    as Record<string, unknown>) ?? {}
    const r    = (cfg.react    as Record<string, unknown>) ?? {}
    const mem  = (cfg.memory   as Record<string, unknown>) ?? {}
    const rt   = (cfg.runtime  as Record<string, unknown>) ?? {}
    const mcp  = (cfg.mcp      as Record<string, unknown>) ?? {}

    setName((cfg.name        as string) ?? '')
    setDescription((cfg.description as string) ?? '')
    setAgentType((cfg.type   as string) ?? 'react')

    setProvider((m.provider  as string) ?? '')
    setModelName((m.name     as string) ?? '')
    setTemperature(String(m.temperature ?? 0.7))
    setMaxTokens(String(m.maxTokens     ?? 4096))
    setBaseUrl((m.baseUrl    as string) ?? '')

    setReactMaxSteps(String(r.maxSteps    ?? 20))
    setToolTimeout(String(r.toolTimeout   ?? 60))
    setThinkTimeout(String(r.thinkTimeout ?? 120))

    setMemoryEnabled(Boolean(mem.enabled))
    setMemorySize(String(mem.size ?? 20))
    setMemoryTtl(String(mem.ttl   ?? 3600))

    setRuntimeEngine((rt.engine    as string) ?? 'cek')
    setCostBudget(String(rt.costBudget ?? 0.5))

    const tools = (mcp.localTools as string[]) ?? []
    setLocalTools(tools)

    setSystemPrompt((cfg.systemPrompt as string) ?? '')
  }, [detailData])

  const createMutation = useMutation({
    mutationFn: ({ cfg, agentName }: { cfg: Record<string, unknown>; agentName: string }) =>
      agentsApi.create({
        name: agentName,
        description,
        config: {
          ...cfg,
          agentId: `${selectedId}-${Date.now()}`,
          name: agentName,
          description,
          type: agentType,
          systemPrompt,
          model: {
            ...((cfg.model as object) ?? {}),
            provider,
            name: modelName,
            temperature: parseFloat(temperature) || 0.7,
            maxTokens: parseInt(maxTokens) || 4096,
            ...(baseUrl ? { baseUrl } : {}),
          },
          react: {
            ...((cfg.react as object) ?? {}),
            maxSteps: parseInt(reactMaxSteps) || 20,
            toolTimeout: parseInt(toolTimeout) || 60,
            thinkTimeout: parseInt(thinkTimeout) || 120,
          },
          memory: {
            ...((cfg.memory as object) ?? {}),
            enabled: memoryEnabled,
            size: parseInt(memorySize) || 20,
            ttl: parseInt(memoryTtl) || 3600,
          },
          runtime: {
            ...((cfg.runtime as object) ?? {}),
            engine: runtimeEngine,
            costBudget: parseFloat(costBudget) || 0.5,
          },
          mcp: {
            ...((cfg.mcp as object) ?? {}),
            localTools,
          },
        },
        tags: [],
        work_dir:   workDir,
        source_dir: sourceDir,
        run_dir:    runDir,
      }),
    onSuccess: (data) => {
      toast.success('智能体创建成功！')
      navigate(`/chat/${data.agent_id}`)
    },
    onError: () => toast.error('创建失败，请重试'),
  })

  function handleSubmit() {
    if (!selectedId || !name.trim() || !provider || !modelName) return
    const cfg = (detailData?.template ?? {}) as Record<string, unknown>
    createMutation.mutate({ cfg, agentName: name.trim() })
  }

  const templates = listData?.templates ?? []
  const canSubmit = !!selectedId && !!name.trim() && !!provider && !!modelName

  return (
    <div className="p-8 max-w-6xl mx-auto">
      <div className="flex items-center gap-3 mb-1">
        <button onClick={() => navigate('/agents')} className="text-gray-400 hover:text-gray-700 transition-colors">
          <ArrowLeft size={18} />
        </button>
        <PageHeader title="从模版导入" description="选择内置模版，快速创建智能体实例" />
      </div>

      {/* Step 1 — Template grid */}
      <section className="mt-6 mb-8">
        <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">
          第一步：选择模版 {templates.length > 0 && `（共 ${templates.length} 个）`}
        </h2>

        {isLoading ? (
          <div className="flex justify-center py-12"><Spinner size={32} /></div>
        ) : templates.length === 0 ? (
          <div className="rounded-xl border border-yellow-200 bg-yellow-50 p-6 text-sm text-yellow-800">
            未找到模版，请确保 <code className="bg-yellow-100 px-1 rounded">agentexample/</code> 存在于项目根目录，且服务从该目录启动。
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
            {templates.map((t: TemplateSummary) => (
              <TemplateCard
                key={t.id}
                t={t}
                selected={selectedId === t.id}
                onClick={() => { setSelectedId(t.id); setTab('basic') }}
              />
            ))}
          </div>
        )}
      </section>

      {/* Step 2 — Configuration form */}
      {selectedId && (
        <Card>
          <div className="flex items-center gap-2 mb-5">
            <div className="w-6 h-6 rounded-full bg-indigo-600 text-white flex items-center justify-center text-xs font-bold shrink-0">
              2
            </div>
            <h2 className="text-sm font-semibold text-gray-900">
              自定义配置
              {loadingDetail && <span className="ml-2 text-gray-400 font-normal text-xs">加载中…</span>}
            </h2>
          </div>

          <Tabs tabs={TABS} active={tab} onChange={setTab} />

          {/* ── 基本设置 ── */}
          {tab === 'basic' && (
            <div className="space-y-4 max-w-lg">
              <Input
                label="智能体名称"
                value={name}
                onChange={e => setName(e.target.value)}
                placeholder="为此实例起一个名字"
              />
              <Textarea
                label="描述"
                rows={3}
                value={description}
                onChange={e => setDescription(e.target.value)}
                placeholder="简短描述此智能体的用途"
              />
              <div>
                <label className="block text-xs font-medium text-gray-700 mb-1">智能体类型</label>
                <select
                  value={agentType}
                  onChange={e => setAgentType(e.target.value)}
                  className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <option value="react">ReAct 智能体（工具调用 + 多步推理）</option>
                  <option value="conversation">对话助手（多轮对话）</option>
                  <option value="compose">流水线（多智能体串联）</option>
                  <option value="groupchat">多智能体群聊</option>
                </select>
              </div>

              {/* ── 三目录配置 ── */}
              <DirSection
                sourceDir={sourceDir} onSourceDir={setSourceDir}
                workDir={workDir}     onWorkDir={setWorkDir}
                runDir={runDir}       onRunDir={setRunDir}
                onBrowse={setDirPickerFor}
              />
            </div>
          )}

          {/* ── 模型配置 ── */}
          {tab === 'model' && (
            <div className="space-y-4 max-w-lg">
              <div>
                <label className="block text-xs font-medium text-gray-700 mb-1">AI 提供商</label>
                <select
                  value={provider}
                  onChange={e => { setProvider(e.target.value); setModelName('') }}
                  className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <option value="">选择提供商</option>
                  {Object.keys(MODEL_MAP).map(p => (
                    <option key={p} value={p}>{p}</option>
                  ))}
                </select>
              </div>
              {provider && (
                <div>
                  <label className="block text-xs font-medium text-gray-700 mb-1">模型</label>
                  <select
                    value={modelName}
                    onChange={e => setModelName(e.target.value)}
                    className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                  >
                    <option value="">选择模型</option>
                    {(MODEL_MAP[provider] ?? []).map(m => (
                      <option key={m} value={m}>{m}</option>
                    ))}
                  </select>
                </div>
              )}
              <div className="grid grid-cols-2 gap-4">
                <Input
                  label="Temperature"
                  type="number"
                  value={temperature}
                  onChange={e => setTemperature(e.target.value)}
                />
                <Input
                  label="Max Tokens"
                  type="number"
                  value={maxTokens}
                  onChange={e => setMaxTokens(e.target.value)}
                />
              </div>
              <Input
                label="Base URL（可选，用于 Ollama 或自定义端点）"
                value={baseUrl}
                onChange={e => setBaseUrl(e.target.value)}
                placeholder="http://localhost:11434"
              />
            </div>
          )}

          {/* ── 行为配置 ── */}
          {tab === 'behavior' && (
            <div className="space-y-4 max-w-lg">
              <p className="text-xs text-gray-500">以下参数控制 ReAct 循环的执行行为。</p>
              <div className="grid grid-cols-3 gap-4">
                <Input
                  label="最大步数"
                  type="number"
                  value={reactMaxSteps}
                  onChange={e => setReactMaxSteps(e.target.value)}
                  hint="每次对话最多执行的工具调用轮次"
                />
                <Input
                  label="工具超时（秒）"
                  type="number"
                  value={toolTimeout}
                  onChange={e => setToolTimeout(e.target.value)}
                  hint="单次工具调用的最长等待时间"
                />
                <Input
                  label="思考超时（秒）"
                  type="number"
                  value={thinkTimeout}
                  onChange={e => setThinkTimeout(e.target.value)}
                  hint="LLM 生成单次思考的最长时间"
                />
              </div>
            </div>
          )}

          {/* ── 记忆 & 运行时 ── */}
          {tab === 'memory' && (
            <div className="space-y-6 max-w-lg">
              <div>
                <h3 className="text-xs font-semibold text-gray-700 uppercase tracking-wide mb-3">记忆配置</h3>
                <div className="space-y-3">
                  <label className="flex items-center gap-3 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={memoryEnabled}
                      onChange={e => setMemoryEnabled(e.target.checked)}
                      className="w-4 h-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                    />
                    <span className="text-sm text-gray-700">启用长期记忆</span>
                  </label>
                  {memoryEnabled && (
                    <div className="grid grid-cols-2 gap-4 pl-7">
                      <Input
                        label="记忆条数上限"
                        type="number"
                        value={memorySize}
                        onChange={e => setMemorySize(e.target.value)}
                        hint="超过上限时自动淘汰旧记忆"
                      />
                      <Input
                        label="TTL（秒）"
                        type="number"
                        value={memoryTtl}
                        onChange={e => setMemoryTtl(e.target.value)}
                        hint="记忆保留时长，0 = 永不过期"
                      />
                    </div>
                  )}
                </div>
              </div>

              <div>
                <h3 className="text-xs font-semibold text-gray-700 uppercase tracking-wide mb-3">运行时引擎</h3>
                <div className="space-y-3">
                  <div>
                    <label className="block text-xs font-medium text-gray-700 mb-1">执行引擎</label>
                    <select
                      value={runtimeEngine}
                      onChange={e => setRuntimeEngine(e.target.value)}
                      className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                    >
                      <option value="cek">CEK Machine（带成本监控 + 循环检测）</option>
                      <option value="recursive">Recursive（简单递归，无开销）</option>
                      <option value="adaptive">Adaptive（自动选择）</option>
                    </select>
                  </div>
                  <Input
                    label="费用上限（USD）"
                    type="number"
                    value={costBudget}
                    onChange={e => setCostBudget(e.target.value)}
                    hint="超过此金额后自动暂停，0 = 不限制"
                  />
                </div>
              </div>
            </div>
          )}

          {/* ── 工具列表 ── */}
          {tab === 'tools' && (
            <div className="max-w-2xl space-y-3">
              <p className="text-xs text-gray-500">
                智能体可调用的工具列表。点击 ✕ 移除工具，在输入框中填写工具名并回车添加。
              </p>
              <ToolTagEditor tools={localTools} onChange={setLocalTools} />
              {localTools.length === 0 && (
                <p className="text-xs text-amber-600 bg-amber-50 rounded-lg px-3 py-2">
                  工具列表为空，智能体将不能调用任何工具。
                </p>
              )}
            </div>
          )}

          {/* ── 系统提示词 ── */}
          {tab === 'prompt' && (
            <div className="max-w-2xl">
              <Textarea
                label="系统提示词"
                rows={16}
                value={systemPrompt}
                onChange={e => setSystemPrompt(e.target.value)}
                hint="来自模版，可直接修改"
              />
            </div>
          )}

          <div className="mt-8 flex gap-3">
            <Button
              onClick={handleSubmit}
              disabled={!canSubmit}
              loading={createMutation.isPending}
              size="lg"
              icon={<Bot size={16} />}
            >
              导入并创建
            </Button>
            <Button variant="secondary" size="lg" onClick={() => navigate('/agents')}>
              取消
            </Button>
          </div>
        </Card>
      )}

      {dirPickerFor === 'work' && (
        <DirPickerModal initial={workDir || undefined}
          onSelect={setWorkDir} onClose={() => setDirPickerFor(null)} />
      )}
      {dirPickerFor === 'source' && (
        <DirPickerModal initial={sourceDir || undefined}
          onSelect={setSourceDir} onClose={() => setDirPickerFor(null)} />
      )}
      {dirPickerFor === 'run' && (
        <DirPickerModal initial={runDir || undefined}
          onSelect={setRunDir} onClose={() => setDirPickerFor(null)} />
      )}
    </div>
  )
}

// ── Shared 3-dir section ──────────────────────────────────────────

function DirSection({
  sourceDir, onSourceDir, workDir, onWorkDir, runDir, onRunDir, onBrowse,
}: {
  sourceDir: string; onSourceDir: (v: string) => void
  workDir: string;   onWorkDir: (v: string) => void
  runDir: string;    onRunDir: (v: string) => void
  onBrowse: (which: 'work' | 'source' | 'run') => void
}) {
  return (
    <div className="space-y-3 rounded-xl border border-indigo-100 bg-indigo-50/40 p-4">
      <p className="text-xs font-semibold text-indigo-700 uppercase tracking-wide">目录配置</p>
      <DirRow label="① 数据来源目录" value={sourceDir} onChange={onSourceDir}
        onBrowse={() => onBrowse('source')}
        placeholder="/Users/me/papers"
        hint="只读输入数据；智能体启动时提示从此处读取" color="blue" />
      <DirRow label="② 工作产物目录" value={workDir} onChange={onWorkDir}
        onBrowse={() => onBrowse('work')}
        placeholder="/Users/me/Documents/my-project"
        hint="Bash 工具初始路径；最终交付成果写这里" color="amber" />
      <DirRow label="③ 运行日志目录" value={runDir} onChange={onRunDir}
        onBrowse={() => onBrowse('run')}
        placeholder="留空 = 自动（工作产物目录 + /workspace）"
        hint="run_*/traces/中间产物；留空自动用工作产物目录" color="green" />
    </div>
  )
}

function DirRow({
  label, hint, value, onChange, onBrowse, placeholder, color,
}: {
  label: string; hint: string; value: string; onChange: (v: string) => void
  onBrowse: () => void; placeholder: string; color: 'amber' | 'blue' | 'green'
}) {
  const iconColor = color === 'amber' ? 'text-amber-500'
    : color === 'blue' ? 'text-blue-500' : 'text-emerald-500'
  return (
    <div>
      <label className="block text-xs font-medium text-gray-700 mb-1">{label}</label>
      <div className="flex gap-2">
        <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
          className="flex-1 rounded-lg border border-gray-300 px-3 py-2 text-sm font-mono
            focus:outline-none focus:ring-2 focus:ring-indigo-500" />
        <button type="button" onClick={onBrowse}
          className="flex items-center gap-1.5 px-3 py-2 border border-gray-300 rounded-lg
            text-sm text-gray-600 hover:bg-gray-50 hover:border-indigo-400 transition-colors shrink-0"
          title="浏览文件夹">
          <FolderOpen size={15} className={iconColor} />浏览
        </button>
      </div>
      <p className="text-xs text-gray-400 mt-1">{hint}</p>
    </div>
  )
}
