import { useEffect, useState } from 'react'
import { Network, Plus, RefreshCw, Server, Trash2, Wifi, WifiOff } from 'lucide-react'
import { api } from '@/api'
import * as interconnect from '@/api/interconnect'
import { useCreateNode, useDeleteNode, useNodes } from '@/api/hooks'
import { setActiveInterconnectNodeId, activeInterconnectNodeId } from '@/api'
import { Button, Card, Input, Modal, PageHeader, Textarea } from '@/components/ui'
import { formatDateTime } from '@/lib/format'
import { toast } from '@/lib/toast'

type Role = 'master' | 'child' | 'none'

export default function Interconnect() {
  const [role, setRole] = useState<Role>('none')
  const [loadingRole, setLoadingRole] = useState(true)
  const [message, setMessage] = useState('')
  const [createOpen, setCreateOpen] = useState(false)
  const [form, setForm] = useState({ name: '', url: '', token: '', remark: '' })
  const [childForm, setChildForm] = useState({ parent_url: '', parent_token: '' })
  const [childStatus, setChildStatus] = useState<{ parent_url: string; parent_token: string; connected: boolean } | null>(null)
  const [activeId, setActiveId] = useState(activeInterconnectNodeId)

  const { data: nodesData, isLoading, refetch, isFetching } = useNodes()
  const createNode = useCreateNode()
  const deleteNode = useDeleteNode()
  const nodes = Array.isArray(nodesData) ? nodesData : []

  async function fetchRole() {
    setLoadingRole(true)
    try {
      const r = await api.settings.get('interconnect', 'interconnect_role')
      setRole(r === 'master' || r === 'child' ? r : 'none')
      if (r === 'child') {
        const st = await interconnect.getChildStatus().catch(() => null)
        setChildStatus(st)
        if (st) {
          setChildForm({
            parent_url: st.parent_url || '',
            parent_token: st.parent_token || '',
          })
        }
      }
    } catch {
      setRole('none')
    } finally {
      setLoadingRole(false)
    }
  }

  useEffect(() => {
    fetchRole()
  }, [])

  async function changeRole(next: Role) {
    try {
      await api.settings.setSection('interconnect', { interconnect_role: next })
      if (next === 'none') {
        await api.settings.setSection('interconnect', {
          interconnect_parent_url: '',
          interconnect_parent_token: '',
        })
        setActiveInterconnectNodeId('')
        setActiveId('')
      }
      setRole(next)
      setMessage(next === 'none' ? '已取消互联角色' : `已切换为${next === 'master' ? '主' : '子'}节点`)
      toast.success(next === 'none' ? '已取消互联角色' : `已切换为${next === 'master' ? '主' : '子'}节点`)
      if (next === 'child') {
        const st = await interconnect.getChildStatus().catch(() => null)
        setChildStatus(st)
      }
      refetch()
    } catch (e: any) {
      setMessage(e?.message || '角色设置失败')
      toast.error(e?.message || '角色设置失败')
    }
  }

  async function saveChildConfig() {
    try {
      await api.settings.setSection('interconnect', {
        interconnect_role: 'child',
        interconnect_parent_url: childForm.parent_url,
        interconnect_parent_token: childForm.parent_token,
      })
      setMessage('子节点配置已保存')
      toast.success('子节点配置已保存')
      const st = await interconnect.getChildStatus().catch(() => null)
      setChildStatus(st)
    } catch (e: any) {
      setMessage(e?.message || '保存失败')
      toast.error(e?.message || '保存失败')
    }
  }

  async function handleCreate() {
    if (!form.name.trim() || !form.url.trim()) {
      setMessage('请填写名称与 URL')
      return
    }
    try {
      await createNode.mutateAsync({
        name: form.name.trim(),
        url: form.url.trim(),
        token: form.token,
        remark: form.remark,
      })
      setCreateOpen(false)
      setForm({ name: '', url: '', token: '', remark: '' })
      setMessage('节点已添加')
      toast.success('节点已添加')
    } catch (e: any) {
      setMessage(e?.message || '添加失败')
      toast.error(e?.message || '添加失败')
    }
  }

  async function refreshNodeStatus(id: string) {
    try {
      await interconnect.getNodeStatus(id)
      refetch()
      toast.success('节点状态已刷新')
    } catch (e: any) {
      toast.error(e?.message || '刷新状态失败')
    }
  }

  function switchActive(id: string, name?: string) {
    const next = activeId === id ? '' : id
    setActiveInterconnectNodeId(next, name)
    setActiveId(next)
    setMessage(next ? `已切换到节点: ${name || id}` : '已切回本机')
    toast.info(next ? `已切换到节点: ${name || id}` : '已切回本机')
    if (next) window.location.reload()
  }

  if (loadingRole) {
    return <div className="p-8 text-sm text-[var(--text-muted)]">正在载入互联配置...</div>
  }

  return (
    <div>
      <PageHeader
        title="互联管理"
        description="多面板主从互联与节点切换"
        actions={
          role === 'master' ? (
            <>
              <Button variant="secondary" onClick={() => refetch()} disabled={isFetching}>
                <RefreshCw size={14} className={isFetching ? 'animate-spin' : ''} />
                刷新
              </Button>
              <Button onClick={() => setCreateOpen(true)}>
                <Plus 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}

      {role === 'none' ? (
        <div className="grid gap-4 md:grid-cols-2">
          <Card className="cursor-pointer space-y-3 p-6 transition hover:border-[var(--border-hover)]" onClick={() => changeRole('master')}>
            <Server size={28} className="text-[var(--text-muted)]" />
            <div className="text-lg font-semibold">作为主节点</div>
            <p className="text-sm text-[var(--text-muted)]">管理并连接多个子面板，可同步任务/变量并切换操作目标。</p>
          </Card>
          <Card className="cursor-pointer space-y-3 p-6 transition hover:border-[var(--border-hover)]" onClick={() => changeRole('child')}>
            <Network size={28} className="text-[var(--text-muted)]" />
            <div className="text-lg font-semibold">作为子节点</div>
            <p className="text-sm text-[var(--text-muted)]">接入已有主面板，接受主节点管理与同步。</p>
          </Card>
        </div>
      ) : null}

      {role === 'master' ? (
        <div className="space-y-4">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div className="text-sm text-[var(--text-muted)]">
              当前角色: 主节点
              {activeId ? ` · 操作目标: 远程节点 ${activeId}` : ' · 操作目标: 本机'}
            </div>
            <Button
              variant="danger"
              size="sm"
              onClick={() => {
                if (confirm('取消主节点角色将断开所有子节点控制，是否继续？')) changeRole('none')
              }}
            >
              取消角色
            </Button>
          </div>

          {isLoading ? (
            <div className="text-sm text-[var(--text-muted)]">加载中...</div>
          ) : nodes.length === 0 ? (
            <Card className="p-8 text-center text-sm text-[var(--text-muted)]">暂无子节点，点击「添加节点」开始</Card>
          ) : (
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              {nodes.map((node) => {
                const online = node.status === 'connected' || node.status === 'online'
                const active = activeId === node.id
                return (
                  <Card key={node.id} className={`p-4 ${active ? 'border-[var(--bg-accent)]' : ''}`}>
                    <div className="mb-3 flex items-start justify-between gap-2">
                      <div className="min-w-0">
                        <div className="font-medium">{node.name}</div>
                        <div className="truncate text-xs text-[var(--text-muted)]">{node.url}</div>
                      </div>
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => {
                          if (confirm('确认删除该节点？')) deleteNode.mutate(node.id)
                        }}
                      >
                        <Trash2 size={14} />
                      </Button>
                    </div>
                    <div className="mb-3 flex items-center gap-2 text-xs">
                      {online ? <Wifi size={14} className="text-green-500" /> : <WifiOff size={14} className="text-red-400" />}
                      <span className={online ? 'text-green-500' : 'text-red-400'}>{online ? '在线' : '离线'}</span>
                      {node.last_heartbeat_at ? (
                        <span className="text-[var(--text-muted)]">· {formatDateTime(node.last_heartbeat_at)}</span>
                      ) : null}
                    </div>
                    {node.metrics ? (
                      <div className="mb-3 grid grid-cols-3 gap-2 text-xs text-[var(--text-muted)]">
                        <div>CPU {node.metrics.cpu_percent?.toFixed?.(0) ?? '-'}%</div>
                        <div>MEM {node.metrics.mem_percent?.toFixed?.(0) ?? '-'}%</div>
                        <div>DISK {node.metrics.disk_percent?.toFixed?.(0) ?? '-'}%</div>
                      </div>
                    ) : null}
                    <div className="flex gap-2">
                      <Button size="sm" variant="secondary" className="flex-1" onClick={() => refreshNodeStatus(node.id)}>
                        状态
                      </Button>
                      <Button size="sm" variant={active ? 'default' : 'secondary'} className="flex-[2]" onClick={() => switchActive(node.id, node.name)}>
                        {active ? '当前操作目标' : '切换到此节点'}
                      </Button>
                    </div>
                  </Card>
                )
              })}
            </div>
          )}
        </div>
      ) : null}

      {role === 'child' ? (
        <div className="space-y-4">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div className="text-sm text-[var(--text-muted)]">
              当前角色: 子节点 · {childStatus?.connected ? '已连接主节点' : '未连接'}
            </div>
            <Button
              variant="danger"
              size="sm"
              onClick={() => {
                if (confirm('取消配置将断开与主节点的连接，是否继续？')) changeRole('none')
              }}
            >
              取消角色
            </Button>
          </div>
          <Card className="max-w-xl space-y-3 p-4">
            <Input
              placeholder="主节点 URL"
              value={childForm.parent_url}
              onChange={(e) => setChildForm((f) => ({ ...f, parent_url: e.target.value }))}
            />
            <Input
              placeholder="主节点 Token"
              value={childForm.parent_token}
              onChange={(e) => setChildForm((f) => ({ ...f, parent_token: e.target.value }))}
            />
            <Button onClick={saveChildConfig}>保存配置</Button>
          </Card>
        </div>
      ) : null}

      <Modal
        open={createOpen}
        title="添加子节点"
        onClose={() => setCreateOpen(false)}
        footer={
          <>
            <Button variant="secondary" onClick={() => setCreateOpen(false)}>
              取消
            </Button>
            <Button onClick={handleCreate} disabled={createNode.isPending}>
              添加
            </Button>
          </>
        }
      >
        <div className="space-y-3">
          <Input placeholder="名称 *" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} />
          <Input placeholder="URL *" value={form.url} onChange={(e) => setForm((f) => ({ ...f, url: e.target.value }))} />
          <Input placeholder="Token" value={form.token} onChange={(e) => setForm((f) => ({ ...f, token: e.target.value }))} />
          <Textarea placeholder="备注" value={form.remark} onChange={(e) => setForm((f) => ({ ...f, remark: e.target.value }))} />
        </div>
      </Modal>
    </div>
  )
}
