import { useCallback, useEffect, useState } from 'react'
import { MonitorDot } from 'lucide-react'
import {
  activeInterconnectNodeId,
  api,
  setActiveInterconnectNodeId,
} from '@/api'
import { getNodes, type InterconnectNode } from '@/api/interconnect'
import { useEventBus } from '@/hooks/useEventBus'
import { SYSTEM_EVENTS } from '@/constants'
import { cn } from '@/lib/utils'

export function NodeSwitcher() {
  const [nodes, setNodes] = useState<InterconnectNode[]>([])
  const [selected, setSelected] = useState(activeInterconnectNodeId || 'local')
  const [isMaster, setIsMaster] = useState(false)
  const [open, setOpen] = useState(false)

  const fetchNodes = useCallback(async () => {
    try {
      const res = await getNodes()
      setNodes(Array.isArray(res) ? res : [])
    } catch {
      setNodes([])
    }
  }, [])

  const updateRoleState = useCallback(
    (role: string) => {
      const master = role === 'master'
      setIsMaster(master)
      if (master) {
        setSelected(activeInterconnectNodeId || 'local')
        fetchNodes()
      } else {
        setNodes([])
        setSelected('local')
        const traveling = !!document.cookie.match(/(?:^| )active_interconnect_node_id=([^;]*)/)
        if (activeInterconnectNodeId && !traveling) {
          setActiveInterconnectNodeId('')
        }
      }
    },
    [fetchNodes],
  )

  useEffect(() => {
    ;(async () => {
      try {
        const role = await api.settings.get('interconnect', 'interconnect_role')
        updateRoleState(role || 'none')
      } catch {
        updateRoleState('none')
      }
    })()
  }, [updateRoleState])

  useEventBus(SYSTEM_EVENTS.INTERCONNECT_ROLE_CHANGED, (role) => {
    updateRoleState(String(role || 'none'))
  })

  useEffect(() => {
    if (!isMaster) return
    const t = window.setInterval(fetchNodes, 120000)
    const onVis = () => {
      if (document.visibilityState === 'visible') fetchNodes()
    }
    document.addEventListener('visibilitychange', onVis)
    return () => {
      clearInterval(t)
      document.removeEventListener('visibilitychange', onVis)
    }
  }, [isMaster, fetchNodes])

  if (!isMaster) return null

  const handleSelect = (val: string) => {
    setSelected(val)
    setOpen(false)
    if (val === 'local') {
      setActiveInterconnectNodeId('')
    } else {
      const name = nodes.find((n) => n.id === val)?.name || ''
      setActiveInterconnectNodeId(val, name)
    }
    window.location.reload()
  }

  const allOptions = [
    { value: 'local', label: '本机节点' },
    ...nodes.map((n) => ({ value: n.id, label: n.name })),
  ]

  const currentLabel = allOptions.find((o) => o.value === selected)?.label || '本机节点'

  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setOpen(!open)}
        className={cn(
          'inline-flex h-8 max-w-[150px] shrink-0 items-center gap-1.5 rounded-md border px-2 text-[11px] leading-none transition-colors',
          selected !== 'local'
            ? 'border-amber-500/30 bg-amber-500/10 text-amber-600 hover:bg-amber-500/15 dark:text-amber-400'
            : 'border-[var(--border)] bg-[var(--bg-primary)] text-[var(--text-secondary)] hover:bg-[var(--bg-hover)]',
        )}
      >
        <MonitorDot size={12} className="shrink-0" />
        <span className="max-w-[100px] truncate">{currentLabel}</span>
      </button>

      {open && (
        <div className="absolute left-0 top-full z-[80] mt-1 min-w-[140px] rounded-md border border-[var(--border)] bg-[var(--bg-secondary)] py-1 shadow-lg">
          {allOptions.map((opt) => (
            <button
              key={opt.value}
              type="button"
              onClick={() => handleSelect(opt.value)}
              className={cn(
                'w-full px-3 py-1.5 text-left text-xs transition-colors',
                opt.value === selected
                  ? 'bg-[var(--bg-selected)] text-[var(--text-primary)]'
                  : 'text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] hover:text-[var(--text-primary)]',
              )}
            >
              {opt.label}
            </button>
          ))}
        </div>
      )}

      {open && (
        <div className="fixed inset-0 z-[70]" onClick={() => setOpen(false)} />
      )}
    </div>
  )
}