import { useEffect, useMemo, useState } from 'react'
import { Copy, Download, Pencil, RefreshCw, Server, Ticket, Trash2 } from 'lucide-react'
import { api, type Agent, type AgentToken, type SchedulerConfig } from '@/api'
import { useAgents, useAgentTokens } from '@/api/hooks'
import { Button, Card, Input, Modal, PageHeader, Switch, Tabs } from '@/components/ui'
import { AGENT_STATUS } from '@/constants'
import { copyToClipboard, formatDateTime } from '@/lib/format'
import { toast } from '@/lib/toast'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { cn } from '@/lib/utils'

const emptyScheduler = (): SchedulerConfig => ({
  worker_count: 4,
  queue_size: 100,
  rate_interval: 0,
  verbose: false,
  strict_queue: false,
})

export default function Agents() {
  const [tab, setTab] = useState<'agents' | 'tokens'>('agents')
  const [keyword, setKeyword] = useState('')
  const [editAgent, setEditAgent] = useState<Agent | null>(null)
  const [detailAgent, setDetailAgent] = useState<Agent | null>(null)
  const [downloadOpen, setDownloadOpen] = useState(false)
  const [tokenFormOpen, setTokenFormOpen] = useState(false)
  const [editingToken, setEditingToken] = useState<AgentToken | null>(null)
  const [agentForm, setAgentForm] = useState({
    name: '',
    description: '',
    enabled: true,
    useScheduler: false,
    scheduler: emptyScheduler(),
  })
  const [tokenForm, setTokenForm] = useState({ remark: '', max_uses: '', expires_at: '' })
  const [message, setMessage] = useState('')
  const qc = useQueryClient()

  const { data: agentsData, isLoading, refetch, isFetching } = useAgents()
  const { data: tokensData, refetch: refetchTokens } = useAgentTokens()
  const agents = Array.isArray(agentsData) ? agentsData : []
  const tokens = Array.isArray(tokensData) ? tokensData : []

  const { data: versionInfo } = useQuery({
    queryKey: ['agentVersion'],
    queryFn: () => api.agents.getVersion(),
  })
  const platforms = Array.isArray(versionInfo?.platforms) ? versionInfo.platforms : []

  const saveAgent = useMutation({
    mutationFn: () =>
      api.agents.update(editAgent!.id, {
        name: agentForm.name,
        description: agentForm.description,
        enabled: agentForm.enabled,
        scheduler_config: agentForm.useScheduler ? agentForm.scheduler : null,
      }),
    onSuccess: () => {
      setEditAgent(null)
      setMessage('Agent 已保存')
      qc.invalidateQueries({ queryKey: ['agents'] })
    },
    onError: (e: any) => setMessage(e?.message || '保存失败'),
  })

  const deleteAgent = useMutation({
    mutationFn: (id: string) => api.agents.delete(id),
    onSuccess: () => {
      setMessage('已删除 Agent')
      qc.invalidateQueries({ queryKey: ['agents'] })
    },
  })

  const forceUpdate = useMutation({
    mutationFn: (id: string) => api.agents.forceUpdate(id),
    onSuccess: () => setMessage('已发送强制更新'),
    onError: (e: any) => setMessage(e?.message || '更新失败'),
  })

  const saveToken = useMutation({
    mutationFn: async () => {
      const payload = {
        remark: tokenForm.remark || undefined,
        max_uses: tokenForm.max_uses ? Number(tokenForm.max_uses) : undefined,
        expires_at: tokenForm.expires_at || undefined,
      }
      if (editingToken) return api.agents.updateToken(editingToken.id, payload)
      return api.agents.createToken(payload)
    },
    onSuccess: () => {
      setTokenFormOpen(false)
      setEditingToken(null)
      setTokenForm({ remark: '', max_uses: '', expires_at: '' })
      setMessage(editingToken ? '令牌已更新' : '令牌已创建')
      qc.invalidateQueries({ queryKey: ['agentTokens'] })
    },
    onError: (e: any) => setMessage(e?.message || '操作失败'),
  })

  const deleteToken = useMutation({
    mutationFn: (id: string) => api.agents.deleteToken(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['agentTokens'] }),
  })

  const filtered = useMemo(() => {
    if (!keyword) return agents
    const q = keyword.toLowerCase()
    return agents.filter((a) =>
      [a.name, a.hostname, a.ip, a.os, a.arch, a.version]
        .filter(Boolean)
        .some((v) => String(v).toLowerCase().includes(q)),
    )
  }, [agents, keyword])

  useEffect(() => {
    if (!editAgent) return
    setAgentForm({
      name: editAgent.name || '',
      description: editAgent.description || '',
      enabled: editAgent.enabled !== false,
      useScheduler: !!editAgent.scheduler_config,
      scheduler: editAgent.scheduler_config || emptyScheduler(),
    })
  }, [editAgent])

  return (
    <div>
      <PageHeader
        title="远程执行"
        description="管理 Agent 节点与接入令牌"
        actions={
          <>
            <Button
              variant="secondary"
              onClick={() => {
                refetch()
                refetchTokens()
              }}
              disabled={isFetching}
            >
              <RefreshCw size={14} className={isFetching ? 'animate-spin' : ''} />
              刷新
            </Button>
            <Button variant="secondary" onClick={() => setDownloadOpen(true)}>
              <Download size={14} />
              下载 Agent
            </Button>
            {tab === 'tokens' ? (
              <Button
                onClick={() => {
                  setEditingToken(null)
                  setTokenForm({ remark: '', max_uses: '', expires_at: '' })
                  setTokenFormOpen(true)
                }}
              >
                <Ticket size={14} />
                创建令牌
              </Button>
            ) : null}
          </>
        }
      />

      {message ? (
        <div className="mb-3 rounded-md border border-[var(--border)] bg-[var(--bg-tertiary)] px-3 py-2 text-sm">{message}</div>
      ) : null}

      <div className="mb-4 flex flex-wrap items-center gap-3">
        <Tabs
          value={tab}
          onValueChange={(v) => setTab(v as 'agents' | 'tokens')}
          items={[
            { value: 'agents', label: '节点列表' },
            { value: 'tokens', label: '接入令牌' },
          ]}
        />
        {tab === 'agents' ? (
          <Input className="max-w-xs" placeholder="搜索节点" value={keyword} onChange={(e) => setKeyword(e.target.value)} />
        ) : null}
        {versionInfo?.version ? (
          <span className="text-sm text-[var(--text-muted)]">Agent 版本: {versionInfo.version}</span>
        ) : null}
      </div>

      {tab === 'agents' ? (
        <Card className="overflow-hidden">
          {isLoading ? (
            <div className="p-6 text-[var(--text-muted)]">加载中...</div>
          ) : filtered.length === 0 ? (
            <div className="p-8 text-center text-sm text-[var(--text-muted)]">
              <Server className="mx-auto mb-2 opacity-50" size={28} />
              暂无 Agent，请先创建令牌并下载安装
            </div>
          ) : (
            <div className="divide-y divide-[var(--border)]">
              {filtered.map((agent) => (
                <div key={agent.id} className="flex flex-col gap-3 p-4 md:flex-row md:items-center md:justify-between">
                  <button className="min-w-0 text-left" onClick={() => setDetailAgent(agent)}>
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="font-medium">{agent.name || agent.hostname || agent.id}</span>
                      <span
                        className={cn(
                          'rounded px-1.5 py-0.5 text-xs',
                          agent.status === AGENT_STATUS.ONLINE
                            ? 'bg-green-500/15 text-green-500'
                            : 'bg-zinc-500/15 text-zinc-400',
                        )}
                      >
                        {agent.status || 'unknown'}
                      </span>
                      {!agent.enabled ? (
                        <span className="rounded bg-amber-500/15 px-1.5 py-0.5 text-xs text-amber-500">已禁用</span>
                      ) : null}
                    </div>
                    <div className="mt-1 text-sm text-[var(--text-muted)]">
                      {[agent.ip, agent.os, agent.arch, agent.version].filter(Boolean).join(' · ')}
                    </div>
                    {agent.last_seen ? (
                      <div className="mt-1 text-xs text-[var(--text-muted)]">最近在线: {formatDateTime(agent.last_seen)}</div>
                    ) : null}
                  </button>
                  <div className="flex flex-wrap gap-2">
                    <Button size="sm" variant="secondary" onClick={() => setEditAgent(agent)}>
                      <Pencil size={14} />
                      编辑
                    </Button>
                    <Button size="sm" variant="secondary" onClick={() => forceUpdate.mutate(agent.id)} disabled={forceUpdate.isPending}>
                      强制更新
                    </Button>
                    <Button
                      size="sm"
                      variant="danger"
                      onClick={() => {
                        if (confirm('确认删除该 Agent？')) deleteAgent.mutate(agent.id)
                      }}
                    >
                      <Trash2 size={14} />
                      删除
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      ) : (
        <Card className="overflow-hidden">
          {tokens.length === 0 ? (
            <div className="p-6 text-[var(--text-muted)]">暂无令牌</div>
          ) : (
            <div className="divide-y divide-[var(--border)]">
              {tokens.map((token) => (
                <div key={token.id} className="flex flex-col gap-3 p-4 md:flex-row md:items-center md:justify-between">
                  <div className="min-w-0">
                    <div className="break-all font-mono text-sm">{token.token}</div>
                    <div className="mt-1 text-xs text-[var(--text-muted)]">
                      备注: {token.remark || '-'} · 使用 {token.used_count}/{token.max_uses || '∞'}
                      {token.expires_at ? ` · 过期 ${formatDateTime(token.expires_at)}` : ''}
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      size="sm"
                      variant="secondary"
                      onClick={async () => {
                        await copyToClipboard(token.token)
                        setMessage('令牌已复制')
                      }}
                    >
                      <Copy size={14} />
                      复制
                    </Button>
                    <Button
                      size="sm"
                      variant="secondary"
                      onClick={() => {
                        setEditingToken(token)
                        setTokenForm({
                          remark: token.remark || '',
                          max_uses: token.max_uses ? String(token.max_uses) : '',
                          expires_at: token.expires_at || '',
                        })
                        setTokenFormOpen(true)
                      }}
                    >
                      <Pencil size={14} />
                    </Button>
                    <Button
                      size="sm"
                      variant="danger"
                      onClick={() => {
                        if (confirm('确认删除该令牌？')) deleteToken.mutate(token.id)
                      }}
                    >
                      <Trash2 size={14} />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </Card>
      )}

      <Modal
        open={!!editAgent}
        title="编辑 Agent"
        onClose={() => setEditAgent(null)}
        size="lg"
        footer={
          <>
            <Button variant="secondary" onClick={() => setEditAgent(null)}>
              取消
            </Button>
            <Button onClick={() => saveAgent.mutate()} disabled={saveAgent.isPending || !agentForm.name.trim()}>
              保存
            </Button>
          </>
        }
      >
        <div className="space-y-3">
          <Input placeholder="名称" value={agentForm.name} onChange={(e) => setAgentForm((f) => ({ ...f, name: e.target.value }))} />
          <Input
            placeholder="描述"
            value={agentForm.description}
            onChange={(e) => setAgentForm((f) => ({ ...f, description: e.target.value }))}
          />
          <label className="flex items-center justify-between text-sm">
            <span>启用</span>
            <Switch checked={agentForm.enabled} onCheckedChange={(v) => setAgentForm((f) => ({ ...f, enabled: v }))} />
          </label>
          <label className="flex items-center justify-between text-sm">
            <span>自定义调度配置</span>
            <Switch
              checked={agentForm.useScheduler}
              onCheckedChange={(v) => setAgentForm((f) => ({ ...f, useScheduler: v }))}
            />
          </label>
          {agentForm.useScheduler ? (
            <div className="grid gap-3 md:grid-cols-3">
              <Input
                type="number"
                placeholder="Worker"
                value={agentForm.scheduler.worker_count}
                onChange={(e) =>
                  setAgentForm((f) => ({
                    ...f,
                    scheduler: { ...f.scheduler, worker_count: Number(e.target.value) || 0 },
                  }))
                }
              />
              <Input
                type="number"
                placeholder="队列"
                value={agentForm.scheduler.queue_size}
                onChange={(e) =>
                  setAgentForm((f) => ({
                    ...f,
                    scheduler: { ...f.scheduler, queue_size: Number(e.target.value) || 0 },
                  }))
                }
              />
              <Input
                type="number"
                placeholder="限速间隔"
                value={agentForm.scheduler.rate_interval}
                onChange={(e) =>
                  setAgentForm((f) => ({
                    ...f,
                    scheduler: { ...f.scheduler, rate_interval: Number(e.target.value) || 0 },
                  }))
                }
              />
            </div>
          ) : null}
        </div>
      </Modal>

      <Modal open={!!detailAgent} title="Agent 详情" onClose={() => setDetailAgent(null)} size="lg">
        {detailAgent ? (
          <div className="space-y-2 text-sm">
            <Row label="ID" value={detailAgent.id} />
            <Row label="名称" value={detailAgent.name} />
            <Row label="主机" value={detailAgent.hostname} />
            <Row label="IP" value={detailAgent.ip} />
            <Row label="系统" value={`${detailAgent.os || '-'} / ${detailAgent.arch || '-'}`} />
            <Row label="版本" value={detailAgent.version} />
            <Row label="状态" value={detailAgent.status} />
            <Row label="最近在线" value={formatDateTime(detailAgent.last_seen)} />
            <Row label="描述" value={detailAgent.description || '-'} />
          </div>
        ) : null}
      </Modal>

      <Modal open={downloadOpen} title="下载 Agent" onClose={() => setDownloadOpen(false)} size="lg">
        <div className="space-y-3">
          <p className="text-sm text-[var(--text-muted)]">
            当前版本: {versionInfo?.version || '-'}。选择平台下载后，使用接入令牌注册到本面板。
          </p>
          <div className="grid gap-2 sm:grid-cols-2">
            {platforms.length === 0 ? (
              <div className="text-sm text-[var(--text-muted)]">暂无可用平台包</div>
            ) : (
              platforms.map((p) => (
                <a key={p.filename} href={api.agents.downloadUrl(p.os, p.arch)} className="inline-flex">
                  <Button variant="secondary" className="w-full justify-start">
                    <Download size={14} />
                    {p.os}/{p.arch}
                    <span className="ml-auto text-xs text-[var(--text-muted)]">{p.filename}</span>
                  </Button>
                </a>
              ))
            )}
          </div>
        </div>
      </Modal>

      <Modal
        open={tokenFormOpen}
        title={editingToken ? '编辑令牌' : '创建令牌'}
        onClose={() => setTokenFormOpen(false)}
        footer={
          <>
            <Button variant="secondary" onClick={() => setTokenFormOpen(false)}>
              取消
            </Button>
            <Button onClick={() => saveToken.mutate()} disabled={saveToken.isPending}>
              保存
            </Button>
          </>
        }
      >
        <div className="space-y-3">
          <Input placeholder="备注" value={tokenForm.remark} onChange={(e) => setTokenForm((f) => ({ ...f, remark: e.target.value }))} />
          <Input
            placeholder="最大使用次数（空=无限）"
            value={tokenForm.max_uses}
            onChange={(e) => setTokenForm((f) => ({ ...f, max_uses: e.target.value }))}
          />
          <Input
            placeholder="过期时间（可选，后端可解析格式）"
            value={tokenForm.expires_at}
            onChange={(e) => setTokenForm((f) => ({ ...f, expires_at: e.target.value }))}
          />
        </div>
      </Modal>
    </div>
  )
}

function Row({ label, value }: { label: string; value?: string | null }) {
  return (
    <div className="flex gap-3 border-b border-[var(--border)] py-2 last:border-0">
      <span className="w-24 shrink-0 text-[var(--text-muted)]">{label}</span>
      <span className="min-w-0 break-all">{value || '-'}</span>
    </div>
  )
}
