/**
 * 侧边栏导航组件
 * 分组式菜单结构，支持折叠/展开，移动端抽屉模式
 */

import { Link, useLocation } from 'react-router-dom'
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import clsx from 'clsx'
import {
  LayoutDashboard, Users, CalendarCheck, UserX,
  Calculator, Shield, BarChart3, ShieldAlert,
  FileSearch, FileText, Stethoscope, HeartPulse, Award,
  Bot, BookMarked,
  Bell, ScrollText, Settings,
  ChevronDown, ChevronRight,
  Building2, CalendarDays, ClipboardList, Heart, CalendarClock,
  Gift, PenTool, Umbrella, GraduationCap, TrendingUp, AlertTriangle,
  DollarSign, Clock, Calendar,
} from 'lucide-react'
import { settingsApi } from '../../lib/api-services'

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

interface NavGroup {
  title: string
  items: NavItem[]
}

const navGroups: NavGroup[] = [
  {
    title: '首页',
    items: [
      { path: '/', label: '工作台', icon: LayoutDashboard },
      { path: '/esign', label: '待签合同', icon: PenTool },
      { path: '/calendar', label: '工作日历', icon: CalendarDays },
    ],
  },
  {
    title: '团队',
    items: [
      { path: '/roster', label: '花名册', icon: Users },
      { path: '/org-chart', label: '组织架构', icon: Building2 },
      { path: '/termination', label: '离职管理', icon: UserX },
      { path: '/training-records', label: '培训记录', icon: GraduationCap },
      { path: '/performance-records', label: '绩效考核', icon: TrendingUp },
      { path: '/disciplinary-records', label: '违纪记录', icon: AlertTriangle },
      { path: '/special-status', label: '特殊员工', icon: Heart },
    ],
  },
  {
    title: '时间',
    items: [
      { path: '/attendance', label: '考勤管理', icon: CalendarCheck },
      { path: '/schedule', label: '排班管理', icon: Calendar },
      { path: '/leave-approval', label: '休假审批', icon: CalendarClock },
    ],
  },
  {
    title: '薪酬',
    items: [
      { path: '/money', label: '薪税管理', icon: Calculator },
      { path: '/social', label: '社保公积金', icon: Shield },
      { path: '/overtime', label: '加班费计算', icon: Clock },
      { path: '/commission-bonus', label: '提成奖金', icon: DollarSign },
      { path: '/salary-dashboard', label: '薪酬分析', icon: BarChart3 },
    ],
  },
  {
    title: '福利保障',
    items: [
      { path: '/commercial-insurance', label: '商业保险', icon: Umbrella },
      { path: '/benefits', label: '员工福利', icon: Gift },
    ],
  },
  {
    title: '合规',
    items: [
      { path: '/risk-center', label: '风险中心', icon: ShieldAlert },
      { path: '/evidence', label: '证据链条', icon: FileSearch },
      { path: '/policies', label: '规章制度', icon: FileText },
    ],
  },
  {
    title: '工具',
    items: [
      { path: '/tools/health-check', label: '用工体检', icon: Stethoscope },
      { path: '/tools/medical-period', label: '医疗期', icon: HeartPulse },
      { path: '/tools/annual-value', label: '年度价值', icon: Award },
    ],
  },
  {
    title: '更多',
    items: [
      { path: '/ai-assistant', label: 'AI顾问', icon: Bot },
      { path: '/templates', label: '文本模板', icon: BookMarked },
      { path: '/notifications', label: '通知管理', icon: Bell },
      { path: '/audit', label: '操作日志', icon: ScrollText },
      { path: '/company-files', label: '公司文件', icon: Building2 },
      { path: '/settings', label: '系统设置', icon: Settings },
    ],
  },
]

/**
 * 侧边栏导航
 */
export default function SidebarNav({ mobileOpen, onClose }: { mobileOpen: boolean; onClose: () => void }) {
  const location = useLocation()
  const { data: orgData } = useQuery<any>({
    queryKey: ['org-settings'],
    queryFn: () => settingsApi.org(),
    staleTime: 300000,
  })
  const isActive = (path: string) => {
    if (path === '/') return location.pathname === '/'
    return location.pathname.startsWith(path)
  }
  const activeGroup = navGroups.find(g => g.items.some(item => isActive(item.path)))
  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
    })
  }

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

      <aside
        className={clsx(
          'fixed md:sticky top-0 left-0 z-50 md:z-auto',
          'w-52 h-screen md: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',
        )}
      >
        {/* 公司名区 */}
        <div className="h-14 flex items-center justify-center px-4 border-b border-gray-200 shrink-0">
          <span className="font-bold text-sm text-gray-900 truncate">{orgData?.name || ''}</span>
        </div>

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

            return (
              <div key={group.title} className={idx > 0 ? 'pt-2 border-t border-gray-100' : ''}>
                {/* 分组标题 */}
                <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="shrink-0 border-t border-gray-200 px-4 py-3">
          <div className="text-xs font-medium text-gray-400">安职通</div>
          <div className="text-[10px] text-gray-300 mt-0.5">用工专家 · 智慧HR</div>
        </div>
      </aside>
    </>
  )
}
