import { useCallback, useRef, useState } from "react"
import { createPortal } from "react-dom"
import { NavLink } from "react-router-dom"
import ProductDropdown from "@/components/productDropdown"
import { cn } from "@/lib/utils"

export function AdminNavMenu() {
  return (
    <nav className="flex-auto flex items-center justify-center gap-1 max-lg:hidden">
      <AdminNavItem to="/">首页</AdminNavItem>
      <AdminMenuItem text="产品购买">
        <ProductDropdown size="sm" />
      </AdminMenuItem>
      <AdminNavItem to="/ipline">IP线路表</AdminNavItem>
      <AdminNavItem to="/softdownload">软件下载</AdminNavItem>
      <AdminNavItem to="/help">帮助/教程</AdminNavItem>
    </nav>
  )
}

function AdminNavItem({
  to,
  children,
}: {
  to: string
  children: React.ReactNode
}) {
  return (
    <NavLink
      to={to}
      className={({ isActive }) =>
        cn(
          "h-10 flex items-center px-3 text-sm rounded-md transition-colors duration-200",
          isActive
            ? "text-blue-600 bg-blue-50"
            : "text-slate-600 hover:text-blue-600 hover:bg-gray-100",
        )
      }
    >
      {children}
    </NavLink>
  )
}

function AdminMenuItem({
  text,
  children,
}: {
  text: string
  children: React.ReactNode
}) {
  const [isOpen, setIsOpen] = useState(false)
  const [pos, setPos] = useState({ top: 0, left: 0 })
  const triggerRef = useRef<HTMLDivElement>(null)
  const timeoutRef = useRef<number | null>(null)

  const updatePosition = useCallback(() => {
    if (triggerRef.current) {
      const rect = triggerRef.current.getBoundingClientRect()
      setPos({ top: rect.bottom + 8, left: rect.left + rect.width / 2 })
    }
  }, [])

  const handleMouseEnter = () => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
      timeoutRef.current = null
    }
    updatePosition()
    setIsOpen(true)
  }

  const handleMouseLeave = () => {
    timeoutRef.current = setTimeout(() => {
      setIsOpen(false)
    }, 150)
  }

  return (
    <div
      ref={triggerRef}
      className="relative h-full flex items-center"
      role="button"
      tabIndex={0}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <button
        className={cn(
          "h-10 flex items-center gap-1 px-3 text-sm rounded-md transition-colors duration-200 pointer-events-none",
          isOpen
            ? "text-blue-600 bg-blue-50"
            : "text-slate-600 group-hover:text-blue-600 group-hover:bg-gray-100",
        )}
      >
        <span>{text}</span>
        <svg
          className={cn(
            "w-3 h-3 transition-transform duration-200",
            isOpen && "rotate-180",
          )}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M19 9l-7 7-7-7"
          />
        </svg>
      </button>

      {createPortal(
        <div
          role="button"
          tabIndex={-1}
          className={cn(
            "fixed transition-all duration-200 z-9999",
            isOpen
              ? "opacity-100 visible translate-y-0"
              : "opacity-0 invisible -translate-y-2 pointer-events-none",
          )}
          style={{
            top: pos.top,
            left: pos.left,
            transform: "translateX(-50%)",
          }}
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
        >
          <div className="bg-white rounded-xl shadow-2xl border border-gray-100/80 p-4 w-140">
            {children}
          </div>
        </div>,
        document.body,
      )}
    </div>
  )
}
