/**
 * 平台管理端侧边栏导航
 * 浅色主题，与企业端配色一致
 */
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useState } from 'react'
import clsx from 'clsx'
import {
  LayoutDashboard, Building2, Users, Shield, LogOut,
  ChevronDown, ChevronRight,
} from 'lucide-react'
import { useAuthStore } from '../../store/authStore'

interface NavItem {
  path: string
  label: string
  icon: typeof LayoutDashboard
}

const navGroups: { title: string; items: NavItem[] }[] = [
  {
    title: '平台管理',
    items: [
      { path: '/platform/dashboard', label: '数据总览', icon: LayoutDashboard },
      { path: '/platform/orgs', label: '企业租户', icon: Building2 },
      { path: '/platform/users', label: '用户管理', icon: Users },
    ],
  },
]

export default function PlatformSidebar({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: () => void }) {
  const location = useLocation()
  const navigate = useNavigate()
  const { user, logout } = useAuthStore()
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set(navGroups.map(g => g.title)))

  const toggleGroup = (title: string) => {
    setExpandedGroups(prev => {
      const next = new Set(prev)
      if (next.has(title)) next.delete(title)
      else next.add(title)
      return next
    })
  }

  const isActive = (path: string) => location.pathname.startsWith(path)

  const handleLogout = () => {
    logout()
    navigate('/platform/login')
  }

  return (
    <>
      {mobileOpen && (
        <div className="fixed inset-0 bg-black/60 z-40 md:hidden" onClick={onClose} aria-label="关闭侧边栏" />
      )}

      <aside
        className={clsx(
          'fixed md:sticky top-0 left-0 z-50 md:z-auto',
          'w-56 h-screen flex-shrink-0',
          'bg-white border-r border-gray-200',
          'flex flex-col',
          'transition-transform duration-200',
          mobileOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0',
        )}
      >
        {/* Logo 区 */}
        <div className="h-14 flex items-center gap-2 px-4 border-b border-gray-200 shrink-0">
          <div className="w-7 h-7 rounded-md bg-primary flex items-center justify-center">
            <Shield className="w-4 h-4 text-white" />
          </div>
          <div>
            <div className="font-bold text-sm text-gray-900">用工专家平台</div>
            <div className="text-[10px] text-primary tracking-wider">ADMIN</div>
          </div>
        </div>

        {/* 导航菜单 */}
        <nav className="flex-1 overflow-y-auto py-3 px-2 space-y-3">
          {navGroups.map((group) => {
            const isExpanded = expandedGroups.has(group.title)
            const hasActiveItem = group.items.some(item => isActive(item.path))

            return (
              <div key={group.title}>
                <button
                  onClick={() => toggleGroup(group.title)}
                  className={clsx(
                    'flex items-center justify-between w-full px-2 py-1.5 text-xs font-medium rounded-md transition-colors',
                    hasActiveItem ? 'text-gray-800' : 'text-gray-500 hover:text-gray-700',
                  )}
                >
                  <span>{group.title}</span>
                  {isExpanded ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
                </button>

                {isExpanded && (
                  <div className="mt-0.5 space-y-0.5">
                    {group.items.map((item) => {
                      const Icon = item.icon
                      const active = isActive(item.path)
                      return (
                        <Link
                          key={item.path}
                          to={item.path}
                          onClick={onClose}
                          className={clsx(
                            'flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors',
                            active
                              ? 'bg-primary/10 text-primary font-medium'
                              : 'text-gray-600 hover:bg-gray-100 hover:text-gray-800',
                          )}
                        >
                          <Icon className="w-4 h-4 flex-shrink-0" />
                          <span className="truncate">{item.label}</span>
                        </Link>
                      )
                    })}
                  </div>
                )}
              </div>
            )
          })}
        </nav>

        {/* 底部用户区 */}
        <div className="border-t border-gray-200 p-3 shrink-0">
          <div className="flex items-center gap-2 mb-2">
            <div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-primary text-sm font-medium">
              {user?.name?.charAt(0) || 'A'}
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-sm text-gray-900 truncate">{user?.name}</div>
              <div className="text-[10px] text-primary">SUPER_ADMIN</div>
            </div>
          </div>
          <button
            onClick={handleLogout}
            className="flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm text-gray-500 hover:bg-gray-100 hover:text-gray-700 transition-colors"
          >
            <LogOut className="w-4 h-4" />
            <span>退出登录</span>
          </button>
        </div>
      </aside>
    </>
  )
}
