import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { Bot, MessageSquare, Trash2, Plus, Settings2, FileCode2, Package } from 'lucide-react'
import toast from 'react-hot-toast'
import { agentsApi, type Agent } from '../api/agents'
import { Card, PageHeader, Badge, EmptyState, Spinner, Button } from '../components/ui'

function providerBadge(config: Record<string, unknown>) {
  const provider = (config?.model as Record<string, unknown>)?.provider as string | undefined
  const colors: Record<string, 'blue' | 'purple' | 'green' | 'yellow'> = {
    'claude-code': 'purple',
    anthropic: 'purple',
    dashscope: 'blue',
    deepseek: 'blue',
    openai: 'green',
    ollama: 'yellow',
  }
  if (!provider) return null
  return <Badge variant={colors[provider] ?? 'default'}>{provider}</Badge>
}

function AgentCard({ agent, onChat, onEdit, onDelete }: { agent: Agent; onChat: () => void; onEdit: () => void; onDelete: () => void }) {
  return (
    <Card className="flex flex-col gap-4 hover:shadow-md transition-shadow">
      <div className="flex items-start justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-indigo-50 rounded-lg shrink-0">
            <Bot size={20} className="text-indigo-600" />
          </div>
          <div className="min-w-0">
            <p className="text-sm font-semibold text-gray-900 truncate">{agent.name}</p>
            <p className="text-xs text-gray-500">v{agent.current_version}</p>
          </div>
        </div>
        <div className="flex items-center gap-1">
          <button onClick={onEdit} className="text-gray-300 hover:text-indigo-500 transition-colors" title="编辑配置">
            <Settings2 size={15} />
          </button>
          <button onClick={onDelete} className="text-gray-300 hover:text-red-500 transition-colors" title="删除">
            <Trash2 size={15} />
          </button>
        </div>
      </div>

      {agent.description && (
        <p className="text-xs text-gray-500 line-clamp-2">{agent.description}</p>
      )}

      <div className="flex items-center gap-2 flex-wrap">
        {providerBadge(agent.config)}
        {agent.tags?.slice(0, 3).map(t => (
          <Badge key={t} variant="default">{t}</Badge>
        ))}
      </div>

      <div className="flex gap-2 mt-auto pt-2 border-t border-gray-100">
        <Button onClick={onChat} size="sm" className="flex-1" icon={<MessageSquare size={13} />}>
          对话
        </Button>
        <Button onClick={onEdit} size="sm" variant="secondary" icon={<Settings2 size={13} />}>
          编辑
        </Button>
      </div>
    </Card>
  )
}

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

  const { data, isLoading } = useQuery({
    queryKey: ['agents'],
    queryFn: agentsApi.list,
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => agentsApi.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['agents'] })
      toast.success('智能体已删除')
    },
    onError: () => toast.error('删除失败'),
  })

  function confirmDelete(agent: Agent) {
    if (window.confirm(`确定要删除「${agent.name}」吗？此操作不可恢复。`)) {
      deleteMutation.mutate(agent.id)
    }
  }

  return (
    <div className="p-8 max-w-6xl mx-auto">
      <PageHeader
        title="智能体"
        description={data ? `共 ${data.agents.length} 个智能体` : undefined}
        action={
          <div className="flex gap-2">
            <Button variant="secondary" onClick={() => navigate('/agents/import')} icon={<FileCode2 size={16} />}>
              开发者模板
              <span className="ml-1.5 text-[9px] bg-gray-200 text-gray-500 px-1.5 py-0.5 rounded font-mono leading-none">高级</span>
            </Button>
            <Button variant="secondary" onClick={() => navigate('/agentpacks')} icon={<Package size={16} />}>
              从智能体包创建
            </Button>
            <Button onClick={() => navigate('/agents/new')} icon={<Plus size={16} />}>
              新建智能体
            </Button>
          </div>
        }
      />

      {isLoading ? (
        <div className="flex justify-center py-16"><Spinner size={32} /></div>
      ) : !data?.agents?.length ? (
        <EmptyState
          icon={<Bot size={48} />}
          title="还没有智能体"
          description="创建第一个智能体，选择模型和角色，即可开始对话。"
          action={
            <Button onClick={() => navigate('/agents/new')} icon={<Plus size={16} />}>
              新建智能体
            </Button>
          }
        />
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {data.agents.map(agent => (
            <AgentCard
              key={agent.id}
              agent={agent}
              onChat={() => navigate(`/chat/${agent.id}`)}
              onEdit={() => navigate(`/agents/${agent.id}/edit`)}
              onDelete={() => confirmDelete(agent)}
            />
          ))}
        </div>
      )}
    </div>
  )
}
