import { NavLink, useLocation } from 'react-router-dom'
import { useState } from 'react'
import {
  LayoutDashboard,
  Upload,
  History,
  Users,
  Settings,
  X,
  Activity,
  ChevronDown,
  Server,
  Mail,
  Cog,
  UsersRound
} from 'lucide-react'

interface SidebarProps {
  isOpen: boolean
  onClose: () => void
}

interface NavItem {
  to: string
  icon: React.ComponentType<{ className?: string }>
  label: string
  children?: NavItem[]
}

const navItems: NavItem[] = [
  { to: '/', icon: LayoutDashboard, label: '仪表盘' },
  { to: '/upload', icon: Upload, label: '上传入库' },
  { to: '/team', icon: UsersRound, label: 'Team 批量处理' },
  { to: '/records', icon: History, label: '加号记录' },
  { to: '/accounts', icon: Users, label: '号池账号' },
  { to: '/monitor', icon: Activity, label: '号池监控' },
  {
    to: '/config',
    icon: Settings,
    label: '系统配置',
    children: [
      { to: '/config', icon: Cog, label: '配置概览' },
      { to: '/config/s2a', icon: Server, label: 'S2A 配置' },
      { to: '/config/email', icon: Mail, label: '邮箱配置' },
    ]
  },
]

export default function Sidebar({ isOpen, onClose }: SidebarProps) {
  const location = useLocation()
  const [expandedItems, setExpandedItems] = useState<string[]>(['/config'])

  const toggleExpand = (path: string) => {
    setExpandedItems(prev =>
      prev.includes(path)
        ? prev.filter(p => p !== path)
        : [...prev, path]
    )
  }

  const isItemActive = (item: NavItem): boolean => {
    if (item.children) {
      return item.children.some(child => location.pathname === child.to)
    }
    return location.pathname === item.to
  }

  const renderNavItem = (item: NavItem, isChild = false) => {
    const hasChildren = item.children && item.children.length > 0
    const isExpanded = expandedItems.includes(item.to)
    const isActive = isItemActive(item)

    if (hasChildren) {
      return (
        <div key={item.to} className="space-y-1">
          <button
            onClick={() => toggleExpand(item.to)}
            className={`w-full flex items-center justify-between gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${isActive
              ? 'bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
              : 'text-slate-600 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800/50'
              }`}
          >
            <div className="flex items-center gap-3">
              <item.icon className="h-5 w-5" />
              {item.label}
            </div>
            <ChevronDown
              className={`h-4 w-4 transition-transform duration-200 ${isExpanded ? 'rotate-180' : ''}`}
            />
          </button>

          {/* 子菜单 */}
          <div className={`ml-4 pl-3 border-l-2 border-slate-200 dark:border-slate-700 space-y-1 overflow-hidden transition-all duration-200 ${isExpanded ? 'max-h-96 opacity-100' : 'max-h-0 opacity-0'
            }`}>
            {item.children?.map(child => renderNavItem(child, true))}
          </div>
        </div>
      )
    }

    return (
      <NavLink
        key={item.to}
        to={item.to}
        onClick={onClose}
        end={item.to === '/config'}
        className={({ isActive }) =>
          `flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${isChild ? 'py-2' : ''
          } ${isActive
            ? isChild
              ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400'
              : 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white shadow-md shadow-blue-500/25'
            : 'text-slate-600 hover:bg-slate-50 dark:text-slate-400 dark:hover:bg-slate-800/50'
          }`
        }
      >
        <item.icon className={`${isChild ? 'h-4 w-4' : 'h-5 w-5'}`} />
        {item.label}
      </NavLink>
    )
  }

  return (
    <>
      {/* Mobile overlay */}
      {isOpen && <div className="fixed inset-0 z-40 bg-black/50 backdrop-blur-sm lg:hidden" onClick={onClose} />}

      {/* Sidebar */}
      <aside
        className={`fixed inset-y-0 left-0 z-50 w-64 bg-white/80 dark:bg-slate-900/90 backdrop-blur-xl border-r border-slate-200 dark:border-slate-800 transform transition-transform duration-300 ease-in-out lg:translate-x-0 lg:static lg:z-auto ${isOpen ? 'translate-x-0' : '-translate-x-full'
          }`}
      >
        {/* Mobile close button */}
        <div className="flex items-center justify-between h-16 px-6 border-b border-slate-200/50 dark:border-slate-800/50 lg:hidden">
          <div className="flex items-center gap-3">
            <div className="h-8 w-8 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-600 flex items-center justify-center shadow-lg shadow-blue-500/30">
              <span className="text-white font-bold text-sm">CP</span>
            </div>
            <span className="font-bold text-lg text-slate-900 dark:text-slate-100 tracking-tight">Codex Pool</span>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
            aria-label="关闭菜单"
          >
            <X className="h-5 w-5 text-slate-600 dark:text-slate-400" />
          </button>
        </div>

        {/* Desktop Header (Logo) */}
        <div className="hidden lg:flex items-center h-16 px-6 border-b border-slate-200/50 dark:border-slate-800/50">
          <div className="flex items-center gap-3">
            <div className="h-8 w-8 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-600 flex items-center justify-center shadow-lg shadow-blue-500/30">
              <span className="text-white font-bold text-sm">CP</span>
            </div>
            <span className="font-bold text-lg text-slate-900 dark:text-slate-100 tracking-tight">Codex Pool</span>
          </div>
        </div>

        {/* Navigation */}
        <nav className="p-4 space-y-1.5">
          {navItems.map(item => renderNavItem(item))}
        </nav>

        {/* Footer */}
        <div className="absolute bottom-0 left-0 right-0 p-4 border-t border-slate-200/50 dark:border-slate-800/50 bg-white/50 dark:bg-slate-900/50 backdrop-blur-sm">
          <div className="text-xs text-slate-500 dark:text-slate-400 text-center font-medium">
            Codex Pool v1.0.0
          </div>
        </div>
      </aside>
    </>
  )
}
