import { useState, useContext } from 'react'
import { NavLink } from 'react-router-dom'
import {
  LayoutDashboard, FileEdit, Image, Calendar, Wallet,
  FolderKanban, CheckSquare, Users, ChevronLeft, ChevronRight, ChevronDown,
  Sparkles, LogOut, User, Settings, Languages, Tag, LayoutList, Receipt, BarChart3, Palette, CalendarDays, AlertCircle
} from 'lucide-react'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../i18n/LanguageContext'

// Standalone items (no category)
const standaloneTop = [
  { to: '/', icon: LayoutDashboard, labelKey: 'nav.dashboard', end: true, tutorial: 'dashboard' },
]

// Grouped items by module
const moduleGroups = [
  {
    module: 'marketing',
    labelKey: 'modules.marketing',
    icon: Calendar,
    items: [
      { to: '/campaigns', icon: Calendar, labelKey: 'nav.campaigns', tutorial: 'campaigns' },
      { to: '/posts', icon: FileEdit, labelKey: 'nav.posts', tutorial: 'posts' },
      { to: '/calendar', icon: CalendarDays, labelKey: 'nav.calendar' },
      { to: '/artefacts', icon: Palette, labelKey: 'nav.artefacts' },
      { to: '/assets', icon: Image, labelKey: 'nav.assets', tutorial: 'assets' },
      { to: '/brands', icon: Tag, labelKey: 'nav.brands' },
      { to: '/translations', icon: Languages, labelKey: 'nav.translations' },
    ],
  },
  {
    module: 'projects',
    labelKey: 'modules.projects',
    icon: FolderKanban,
    items: [
      { to: '/projects', icon: LayoutList, labelKey: 'nav.projects' },
      { to: '/tasks', icon: CheckSquare, labelKey: 'nav.tasks', tutorial: 'tasks' },
    ],
  },
  {
    module: 'finance',
    labelKey: 'modules.finance',
    icon: Wallet,
    minRole: 'manager',
    items: [
      { to: '/finance', icon: BarChart3, labelKey: 'nav.financeDashboard' },
      { to: '/budgets', icon: Receipt, labelKey: 'nav.budgets' },
    ],
  },
  {
    module: 'issues',
    labelKey: 'modules.issues',
    icon: AlertCircle,
    items: [
      { to: '/issues', icon: AlertCircle, labelKey: 'nav.issues' },
    ],
  },
]

const standaloneBottom = [
  { to: '/team', icon: Users, labelKey: 'nav.team', tutorial: 'team' },
]

const ROLE_LEVEL = { contributor: 0, manager: 1, superadmin: 2 }

export default function Sidebar({ collapsed, setCollapsed }) {
  const { user: currentUser, logout, hasModule } = useAuth()
  const { t, lang, setLang } = useLanguage()
  const userLevel = ROLE_LEVEL[currentUser?.role] ?? 0

  // Track expanded state for each module group
  const [expandedGroups, setExpandedGroups] = useState(() => {
    const initial = {}
    moduleGroups.forEach(g => { initial[g.module] = true })
    return initial
  })

  const toggleGroup = (module) => {
    setExpandedGroups(prev => ({ ...prev, [module]: !prev[module] }))
  }

  const navLink = ({ to, icon: Icon, labelKey, end, tutorial }, { sub = false } = {}) => (
    <NavLink
      key={to}
      to={to}
      end={end}
      data-tutorial={tutorial}
      className={({ isActive }) =>
        `flex items-center gap-3 rounded-lg font-medium transition-all duration-200 group ${
          sub ? 'px-3 py-1.5 ms-5 text-[13px]' : 'px-3 py-2 text-sm'
        } ${
          isActive
            ? 'bg-white/15 text-white shadow-sm sidebar-active-glow'
            : 'text-text-on-dark-muted hover:bg-white/8 hover:text-white'
        }`
      }
    >
      <Icon className={`${sub ? 'w-3.5 h-3.5' : 'w-5 h-5'} shrink-0`} />
      {!collapsed && <span className="animate-fade-in whitespace-nowrap">{t(labelKey)}</span>}
    </NavLink>
  )

  const visibleGroups = moduleGroups.filter(group => {
    if (!hasModule(group.module)) return false
    if (group.minRole && userLevel < (ROLE_LEVEL[group.minRole] ?? 0)) return false
    return true
  })

  return (
    <aside
      className={`sidebar fixed top-0 h-screen bg-sidebar flex flex-col z-30 transition-all duration-300 ${
        collapsed ? 'w-[68px]' : 'w-[260px]'
      }`}
    >
      {/* Logo */}
      <div className="flex items-center gap-3 px-4 h-16 border-b border-white/10 shrink-0">
        <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-indigo-400 via-purple-500 to-pink-500 flex items-center justify-center shrink-0 shadow-lg shadow-indigo-500/30">
          <Sparkles className="w-5 h-5 text-white" />
        </div>
        {!collapsed && (
          <div className="animate-fade-in overflow-hidden">
            <h1 className="text-white font-bold text-sm leading-tight whitespace-nowrap">{t('app.name')}</h1>
            <p className="text-text-on-dark-muted text-xs whitespace-nowrap">{t('app.subtitle')}</p>
          </div>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 py-3 px-3 space-y-0.5 overflow-y-auto">
        {/* Dashboard (always visible, standalone) */}
        {standaloneTop.map(item => navLink(item))}

        {/* Module groups */}
        {visibleGroups.map(group => {
          const GroupIcon = group.icon
          const isExpanded = expandedGroups[group.module]

          if (collapsed) {
            // When collapsed, just show the sub-item icons
            return group.items.map(item => navLink(item))
          }

          return (
            <div key={group.module} className="mt-3">
              {/* Category header */}
              <button
                onClick={() => toggleGroup(group.module)}
                className="w-full flex items-center gap-2 px-3 py-2 text-xs font-bold uppercase tracking-wide text-text-on-dark-muted hover:text-white transition-colors rounded-lg hover:bg-white/5"
              >
                <GroupIcon className="w-4 h-4 shrink-0 opacity-70" />
                <span className="flex-1 text-start">{t(group.labelKey)}</span>
                <ChevronDown className={`w-3.5 h-3.5 opacity-60 transition-transform ${isExpanded ? '' : '-rotate-90'}`} />
              </button>

              {/* Sub-items */}
              {isExpanded && (
                <div className="space-y-0.5 mt-0.5">
                  {group.items.map(item => navLink(item, { sub: true }))}
                </div>
              )}
            </div>
          )
        })}

        {/* Team (always visible) */}
        <div className="mt-3 pt-2 border-t border-white/8">
          {standaloneBottom.map(item => navLink(item))}
        </div>

        {/* Settings (visible to all) */}
        <NavLink
          to="/settings"
          className={({ isActive }) =>
            `flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 group ${
              isActive
                ? 'bg-white/15 text-white shadow-sm'
                : 'text-text-on-dark-muted hover:bg-white/8 hover:text-white'
            }`
          }
        >
          <Settings className="w-5 h-5 shrink-0" />
          {!collapsed && <span className="animate-fade-in whitespace-nowrap">{t('nav.settings')}</span>}
        </NavLink>
      </nav>

      {/* Current User & Logout */}
      <div className="border-t border-white/10 shrink-0">
        {currentUser && !collapsed && (
          <div className="p-3 border-b border-white/10">
            <div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-white/5">
              <div className="w-8 h-8 rounded-full bg-brand-primary flex items-center justify-center shrink-0">
                {currentUser.avatar ? (
                  <img src={currentUser.avatar} alt={currentUser.name} className="w-full h-full rounded-full object-cover" />
                ) : (
                  <User className="w-4 h-4 text-white" />
                )}
              </div>
              <div className="flex-1 min-w-0 animate-fade-in">
                <p className="text-white text-sm font-medium truncate">{currentUser.name}</p>
                <p className="text-text-on-dark-muted text-xs truncate capitalize">{currentUser.role}</p>
              </div>
            </div>
          </div>
        )}

        {!collapsed && (
          <>
            {/* Language Toggle */}
            <div className="px-3 pb-3">
              <button
                onClick={() => setLang(lang === 'en' ? 'ar' : 'en')}
                className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-text-on-dark-muted hover:bg-white/8 hover:text-white transition-colors text-sm"
              >
                <Languages className="w-4 h-4" />
                <span className="animate-fade-in">{lang === 'en' ? 'عربي' : 'English'}</span>
              </button>
            </div>

            {/* Logout */}
            <div className="px-3 pb-3">
              <button
                onClick={logout}
                className="w-full flex items-center gap-2 px-3 py-2 rounded-lg text-text-on-dark-muted hover:bg-white/8 hover:text-white transition-colors text-sm"
              >
                <LogOut className="w-4 h-4" />
                <span className="animate-fade-in">{t('nav.logout')}</span>
              </button>
            </div>
          </>
        )}

        {/* Collapse toggle */}
        <div className="p-3 border-t border-white/10">
          <button
            onClick={() => setCollapsed(!collapsed)}
            className="w-full flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-text-on-dark-muted hover:bg-white/8 hover:text-white transition-colors text-sm"
          >
            {collapsed ? <ChevronRight className="w-4 h-4" /> : (
              <>
                <ChevronLeft className="w-4 h-4" />
                <span className="animate-fade-in">{t('nav.collapse')}</span>
              </>
            )}
          </button>
        </div>
      </div>
    </aside>
  )
}
