import { useState, useRef, useEffect, useCallback } from 'react'
import { createPortal } from 'react-dom'
import { Monitor, MessageSquare, ChevronDown, Eye, Pencil, Smartphone } from 'lucide-react'
import type { Channel } from '../../types/protocol'

interface ChannelSelectorProps {
  channels: Channel[]
  selectedChannel: string
  onSelectChannel: (channelId: string) => void
}

const CHANNEL_ICONS: Record<string, { icon: React.ReactNode; color: string }> = {
  cli: {
    icon: <Monitor className="h-3.5 w-3.5" />,
    color: 'var(--accent-amber)',
  },
  websocket: {
    icon: <MessageSquare className="h-3.5 w-3.5" />,
    color: 'var(--accent-cyan)',
  },
  feishu: {
    icon: <Smartphone className="h-3.5 w-3.5" />,
    color: 'var(--accent-blue)',
  },
  wechat: {
    icon: <Smartphone className="h-3.5 w-3.5" />,
    color: 'var(--accent-green)',
  },
  weixin: {
    icon: <Smartphone className="h-3.5 w-3.5" />,
    color: 'var(--accent-green)',
  },
}

const DEFAULT_ICON = {
  icon: <MessageSquare className="h-3.5 w-3.5" />,
  color: 'var(--text-muted)',
}

export function ChannelSelector({
  channels,
  selectedChannel,
  onSelectChannel,
}: ChannelSelectorProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [dropdownPos, setDropdownPos] = useState<{ top: number; right: number }>({ top: 0, right: 0 })
  const triggerRef = useRef<HTMLButtonElement>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)
  const selected = channels.find((c) => c.id === selectedChannel)
  const iconConfig = selected ? (CHANNEL_ICONS[selected.id] || DEFAULT_ICON) : DEFAULT_ICON

  // Calculate dropdown position when opening
  const updatePosition = useCallback(() => {
    if (triggerRef.current) {
      const rect = triggerRef.current.getBoundingClientRect()
      setDropdownPos({
        top: rect.bottom + 8,
        right: window.innerWidth - rect.right,
      })
    }
  }, [])

  useEffect(() => {
    if (isOpen) {
      updatePosition()
      window.addEventListener('resize', updatePosition)
      window.addEventListener('scroll', updatePosition, true)
      return () => {
        window.removeEventListener('resize', updatePosition)
        window.removeEventListener('scroll', updatePosition, true)
      }
    }
  }, [isOpen, updatePosition])

  // Close on outside click
  useEffect(() => {
    if (!isOpen) return
    const handleClick = (e: MouseEvent) => {
      const target = e.target as Node
      if (
        dropdownRef.current && !dropdownRef.current.contains(target) &&
        triggerRef.current && !triggerRef.current.contains(target)
      ) {
        setIsOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [isOpen])

  // Close on Escape
  useEffect(() => {
    if (!isOpen) return
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setIsOpen(false)
    }
    document.addEventListener('keydown', handleKey)
    return () => document.removeEventListener('keydown', handleKey)
  }, [isOpen])

  return (
    <>
      {/* Trigger Button */}
      <button
        ref={triggerRef}
        onClick={() => setIsOpen(!isOpen)}
        className={`
          group flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm w-44 justify-between
          transition-all duration-200 ease-out
          ${isOpen
            ? 'border-[var(--accent-cyan)]/40 bg-[var(--overlay-subtle)] shadow-[0_0_12px_var(--shadow-glow-sm)]'
            : 'border-[var(--border-color)] hover:border-[var(--border-accent)] hover:bg-[var(--overlay-hover)]'
          }
        `}
      >
        {/* Channel icon */}
        <span
          className="transition-colors duration-200 flex-shrink-0"
          style={{ color: iconConfig.color }}
        >
          {iconConfig.icon}
        </span>

        {/* Channel name */}
        <span className="flex-1 min-w-0 text-[var(--text-primary)] font-medium text-xs tracking-wide truncate text-center">
          {selected?.name || '选择通道'}
        </span>

        {/* Right indicators */}
        <span className="flex items-center gap-1 flex-shrink-0">
          {selected ? (
            <span
              className={`h-1.5 w-1.5 rounded-full ${
                selected.isWritable ? 'bg-emerald-400 shadow-[0_0_6px_rgba(52,211,153,0.5)]' : 'bg-zinc-500'
              }`}
            />
          ) : (
            <span className="w-1.5" />
          )}
          <ChevronDown
            className={`h-3.5 w-3.5 text-[var(--text-muted)] transition-transform duration-200 ${
              isOpen ? 'rotate-180' : ''
            }`}
          />
        </span>
      </button>

      {/* Dropdown Panel — rendered to body via Portal to avoid stacking context clipping */}
      {isOpen && createPortal(
        <div
          ref={dropdownRef}
          className="fixed z-[9999] w-56 animate-slide-in"
          style={{ top: dropdownPos.top, right: dropdownPos.right }}
        >
          <div
            className="
              rounded-xl border border-[var(--border-color)]
              bg-[var(--bg-secondary)]/95 backdrop-blur-xl
              shadow-2xl shadow-black/40
              overflow-hidden
            "
          >
            {/* Channel List */}
            <div className="py-1">
              {channels.length === 0 ? (
                <div className="px-4 py-6 text-center text-xs text-[var(--text-muted)]">
                  暂无可用通道
                </div>
              ) : (
                channels.map((channel, index) => {
                  const cfg = CHANNEL_ICONS[channel.id] || DEFAULT_ICON
                  const isActive = channel.id === selectedChannel

                  return (
                    <button
                      key={channel.id}
                      onClick={() => {
                        onSelectChannel(channel.id)
                        setIsOpen(false)
                      }}
                      className={`
                        group/item relative w-full flex items-center gap-3 px-4 py-2.5 text-left
                        transition-all duration-150
                        hover:bg-[var(--overlay-hover)]
                        ${isActive ? 'bg-[var(--overlay-subtle)]' : ''}
                      `}
                      style={{
                        animationDelay: `${index * 40}ms`,
                        animation: 'fade-in 0.2s ease-out both',
                      }}
                    >
                      {/* Left accent bar */}
                      <div
                        className={`
                          absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 rounded-r-full
                          transition-all duration-200
                          ${isActive ? 'bg-[var(--accent-cyan)] shadow-[0_0_8px_var(--accent-cyan)]' : 'bg-transparent'}
                        `}
                      />

                      {/* Icon */}
                      <span
                        className={`
                          flex-shrink-0 transition-colors duration-200
                          ${isActive ? 'opacity-100' : 'opacity-60 group-hover/item:opacity-100'}
                        `}
                        style={{ color: cfg.color }}
                      >
                        {cfg.icon}
                      </span>

                      {/* Name + Description */}
                      <div className="flex-1 min-w-0">
                        <div
                          className={`text-sm truncate transition-colors duration-200 ${
                            isActive
                              ? 'text-[var(--text-primary)] font-medium'
                              : 'text-[var(--text-secondary)] group-hover/item:text-[var(--text-primary)]'
                          }`}
                        >
                          {channel.name}
                        </div>
                        {channel.description && (
                          <div className="text-[10px] text-[var(--text-muted)] truncate mt-0.5">
                            {channel.description}
                          </div>
                        )}
                      </div>

                      {/* Writable badge */}
                      <span
                        className={`
                          flex-shrink-0 flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]
                          transition-all duration-200
                          ${channel.isWritable
                            ? 'bg-emerald-400/10 text-emerald-400'
                            : 'bg-zinc-500/10 text-zinc-500'
                          }
                          ${isActive && channel.isWritable ? 'bg-emerald-400/15' : ''}
                        `}
                      >
                        {channel.isWritable ? (
                          <Pencil className="h-2.5 w-2.5" />
                        ) : (
                          <Eye className="h-2.5 w-2.5" />
                        )}
                        <span>{channel.isWritable ? '可写' : '只读'}</span>
                      </span>
                    </button>
                  )
                })
              )}
            </div>
          </div>
        </div>,
        document.body
      )}
    </>
  )
}
