import { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { 
  LayoutDashboard, BookOpen, 
  Calendar, Mail, CalendarDays, LogOut,
  Shield, Users as UsersIcon, Menu, X,
  Home, ClipboardList, CreditCard, FileText, BarChart3,
  Building2, TrendingUp, Settings, Edit3, Sun, Moon, Bell
} from 'lucide-react';
import { useThemeStore } from '../store/theme';

interface User {
  id: number;
  email: string;
  role: 'admin' | 'teacher' | 'student' | 'parent' | 'principal' | 'hr' | 'bursar';
  first_name: string;
  last_name: string;
}

interface NavProps {
  user: User | null;
  onLogout: () => void;
}

const NAV_CONFIG = {
  admin: [
    { path: '/dashboard/admin', label: 'Dashboard', icon: LayoutDashboard },
    { path: '/users', label: 'Users', icon: UsersIcon },
    { path: '/departments', label: 'Departments', icon: Building2 },
    { path: '/notice-board', label: 'Notice Board', icon: Bell },
    { path: '/library', label: 'Library', icon: BookOpen },
    { path: '/reports', label: 'Reports', icon: BarChart3 },
    { path: '/settings', label: 'Settings', icon: Shield },
  ],
  principal: [
    { path: '/dashboard/admin', label: 'Dashboard', icon: Home },
    { path: '/users', label: 'Staff & Students', icon: UsersIcon },
    { path: '/departments', label: 'Departments', icon: Building2 },
    { path: '/notice-board', label: 'Notice Board', icon: Bell },
    { path: '/library', label: 'Library', icon: BookOpen },
    { path: '/teacher-tools', label: 'Curriculum', icon: ClipboardList },
    { path: '/finance/payroll/runs', label: 'Payroll', icon: CreditCard },
    { path: '/messages', label: 'Messages', icon: Mail },
  ],
  hr: [
    { path: '/dashboard/admin', label: 'Dashboard', icon: Home },
    { path: '/notice-board', label: 'Notice Board', icon: Bell },
    { path: '/hr/records', label: 'Staff Records', icon: UsersIcon },
    { path: '/hr/leave', label: 'Leave', icon: Calendar },
    { path: '/hr/attendance', label: 'Attendance', icon: ClipboardList },
    { path: '/messages', label: 'Messages', icon: Mail },
  ],
  bursar: [
    { path: '/dashboard/admin', label: 'Dashboard', icon: Home },
    { path: '/notice-board', label: 'Notice Board', icon: Bell },
    { path: '/finance/payroll/runs', label: 'Payroll', icon: CreditCard },
    { path: '/fees', label: 'Fees', icon: CreditCard },
    { path: '/reports', label: 'Finance Reports', icon: BarChart3 },
    { path: '/messages', label: 'Messages', icon: Mail },
  ],
  teacher: [
    { path: '/dashboard/teacher', label: 'Dashboard', icon: Home },
    { path: '/notice-board', label: 'Notice Board', icon: Bell },
    { path: '/my-courses', label: 'My Courses', icon: BookOpen },
    { path: '/teacher-tools', label: 'Teacher Tools', icon: ClipboardList },
    { path: '/assignments', label: 'Assignments', icon: FileText },
    { path: '/students', label: 'My Students', icon: UsersIcon },
    { path: '/attendance', label: 'Attendance', icon: ClipboardList },
    { path: '/messages', label: 'Messages', icon: Mail },
    { path: '/events', label: 'Schedule', icon: CalendarDays },
  ],
  student: [
    { path: '/dashboard/student', label: 'My Dashboard', icon: Home },
    { path: '/notice-board', label: 'Notice Board', icon: Bell },
    { path: '/my-courses', label: 'My Courses', icon: BookOpen },
    { path: '/assignments', label: 'Assignments', icon: FileText },
    { path: '/exams', label: 'Exam Portal', icon: ClipboardList },
    { path: '/grades', label: 'Grades', icon: BarChart3 },
    { path: '/attendance', label: 'My Attendance', icon: ClipboardList },
    { path: '/messages', label: 'Messages', icon: Mail },
    { path: '/events', label: 'Events', icon: CalendarDays },
  ],
  parent: [
    { path: '/dashboard/parent', label: 'Dashboard', icon: Home },
    { path: '/notice-board', label: 'Notice Board', icon: Bell },
    { path: '/academic-progress', label: 'Progress', icon: TrendingUp },
    { path: '/calendar', label: 'Schedule', icon: Calendar },
    { path: '/attendance', label: 'Attendance', icon: ClipboardList },
    { path: '/fees', label: 'Fees', icon: CreditCard },
    { path: '/messages', label: 'Messages', icon: Mail },
    { path: '/events', label: 'Events', icon: CalendarDays },
  ],
};

const ROLE_COLORS = {
  admin: { bg: 'rgba(230, 238, 249, 0.1)', color: '#ffffff', border: 'rgba(194, 212, 240, 0.2)', active: '#ffffff', activeBg: '#0047AB' },
  principal: { bg: 'rgba(230, 238, 249, 0.1)', color: '#ffffff', border: 'rgba(194, 212, 240, 0.2)', active: '#ffffff', activeBg: '#6B46C1' },
  hr: { bg: 'rgba(230, 238, 249, 0.1)', color: '#ffffff', border: 'rgba(194, 212, 240, 0.2)', active: '#ffffff', activeBg: '#3182CE' },
  bursar: { bg: 'rgba(230, 238, 249, 0.1)', color: '#ffffff', border: 'rgba(194, 212, 240, 0.2)', active: '#ffffff', activeBg: '#38A169' },
  teacher: { bg: 'rgba(224, 242, 242, 0.1)', color: '#ffffff', border: 'rgba(179, 223, 224, 0.2)', active: '#ffffff', activeBg: '#008080' },
  student: { bg: 'rgba(232, 245, 233, 0.1)', color: '#ffffff', border: 'rgba(200, 230, 201, 0.2)', active: '#ffffff', activeBg: '#4CAF50' },
  parent: { bg: 'rgba(255, 245, 224, 0.1)', color: '#ffffff', border: 'rgba(255, 230, 179, 0.2)', active: '#ffffff', activeBg: '#FFA500' },
};

export default function Nav({ user, onLogout }: NavProps) {
  const location = useLocation();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  
  const role = user?.role || 'admin';
  const navLinks = NAV_CONFIG[role] || NAV_CONFIG.admin;
  const colors = ROLE_COLORS[role] || ROLE_COLORS.admin;
  const { toggleTheme, resolvedTheme } = useThemeStore();

  const SidebarContent = () => (
    <div className="flex flex-col h-full py-6 px-4">
      {/* Brand */}
      <div className="mb-10 px-2">
        <div className="flex items-center gap-3">
          <img
            src="/logo.svg"
            alt="NextGen Learning"
            className="w-20 h-20 object-contain p-1 bg-blue-400 rounded-3xl shadow-md"
          />
          <div>
            <h1 className="text-white font-bold text-lg leading-tight tracking-tight">NextGen</h1>
            <p className="text-[#FFA500] text-[0.6rem] font-bold tracking-[2px] uppercase">{role} Portal</p>
          </div>
        </div>
      </div>

      {/* Nav Links */}
      <nav className="flex-1 flex flex-col gap-1.5 overflow-y-auto custom-scrollbar">
        {navLinks.map(({ path, label, icon: Icon }) => {
          const isActive = location.pathname === path || 
            (path !== '/' && path !== '/dashboard/' + role && location.pathname.startsWith(path));
          
          return (
            <Link 
              key={path} 
              to={path}
              onClick={() => setMobileMenuOpen(false)}
              className={`flex items-center gap-3 px-4 py-2.5 rounded-lg no-underline transition-all duration-200 group ${isActive ? 'bg-white/15 text-white shadow-sm ring-1 ring-white/20' : 'text-white/70 hover:bg-white/5 hover:text-white'}`}
            >
              <Icon size={20} className={isActive ? 'opacity-100' : 'opacity-60 group-hover:opacity-100'} />
              <span className="text-[0.9rem] font-medium">{label}</span>
            </Link>
          );
        })}
      </nav>

      {/* Footer / User Actions */}
      <div className="mt-auto pt-6 border-t border-white/10 space-y-4">
        {/* User Info */}
        <div className="px-2 py-3 rounded-xl bg-white/5 border border-white/10">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-full bg-gradient-to-br from-[#667eea] to-[#764ba2] flex items-center justify-center font-bold text-xs text-white uppercase shadow-inner">
              {user?.first_name?.[0]}{user?.last_name?.[0]}
            </div>
            <div className="flex flex-col min-w-0 flex-1">
              <div className="flex items-center justify-between">
                <Link to="/profile" className="text-white text-sm font-semibold truncate leading-tight hover:text-[#FFA500] transition-colors">
                    {user?.first_name} {user?.last_name}
                </Link>
                <Link to="/profile" className="p-1 text-white/40 hover:text-white transition-colors" title="Edit Profile">
                    <Edit3 size={14} />
                </Link>
              </div>
              <span className="text-white/40 text-[0.65rem] truncate">
                {user?.email}
              </span>
            </div>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="grid grid-cols-3 gap-2">
          <button 
            onClick={toggleTheme}
            className="flex items-center justify-center p-2.5 rounded-lg bg-white/5 text-white/70 hover:bg-white/10 hover:text-white transition-colors border border-white/5"
            title={`Switch to ${resolvedTheme === 'dark' ? 'light' : 'dark'} mode`}
          >
            {resolvedTheme === 'dark' ? <Sun size={18} /> : <Moon size={18} />}
          </button>
          <Link 
            to="/settings"
            className="flex items-center justify-center p-2.5 rounded-lg bg-white/5 text-white/70 hover:bg-white/10 hover:text-white transition-colors border border-white/5"
          >
            <Settings size={18} />
          </Link>
          <button 
            onClick={onLogout}
            className="flex items-center justify-center p-2.5 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white transition-all border border-red-500/20"
          >
            <LogOut size={18} />
          </button>
        </div>

        {/* System Status */}
        <div className="px-3 py-2 bg-black/20 rounded-lg text-[0.6rem] text-white/30 font-mono">
          <div className="flex items-center gap-2 mb-1">
            <div className="w-1.5 h-1.5 bg-emerald-500 rounded-full animate-pulse"></div>
            <span>System: Stable</span>
          </div>
          <p>DB: Connected</p>
        </div>
      </div>
    </div>
  );

  const BottomNav = () => {
    // Select top 4 links for bottom nav, others stay in sidebar
    const bottomLinks = navLinks.slice(0, 4);
    
    return (
      <nav className="lg:hidden fixed bottom-0 left-0 right-0 h-20 bg-[#002147] border-t border-white/10 z-[100] px-2 flex items-center justify-around shadow-[0_-8px_30px_rgb(0,0,0,0.12)] backdrop-blur-lg bg-opacity-95">
        {bottomLinks.map(({ path, label, icon: Icon }) => {
          const isActive = location.pathname === path || 
            (path !== '/' && path !== '/dashboard/' + role && location.pathname.startsWith(path));
          
          return (
            <Link 
              key={path} 
              to={path}
              className={`flex flex-col items-center gap-1.5 px-3 py-2 rounded-xl transition-all duration-200 ${isActive ? 'text-[#FFA500]' : 'text-white/40'}`}
            >
              <Icon size={22} strokeWidth={isActive ? 2.5 : 2} />
              <span className="text-[0.6rem] font-black uppercase tracking-widest">{label.split(' ')[0]}</span>
            </Link>
          );
        })}
        <button 
          onClick={() => setMobileMenuOpen(true)}
          className={`flex flex-col items-center gap-1.5 px-3 py-2 rounded-xl transition-all duration-200 ${mobileMenuOpen ? 'text-[#FFA500]' : 'text-white/40'}`}
        >
          <Menu size={22} strokeWidth={mobileMenuOpen ? 2.5 : 2} />
          <span className="text-[0.6rem] font-black uppercase tracking-widest">More</span>
        </button>
      </nav>
    );
  };

  return (
    <>
      {/* Mobile Header (Sticky) */}
      <header className="lg:hidden fixed top-0 left-0 right-0 h-16 bg-[#002147] border-b border-white/10 z-[100] px-4 flex items-center justify-between shadow-lg">
        <Link to="/" className="flex items-center gap-2">
          <img src="/logo.svg" alt="Logo" className="w-10 h-10 object-contain p-1 bg-gray-100 rounded-3xl shadow-md" />
          <span className="text-white font-bold text-sm">NextGen</span>
        </Link>
        <div className="flex items-center gap-3">
            <Link to="/profile" className="w-8 h-8 rounded-full bg-white/10 flex items-center justify-center text-white text-[0.6rem] font-bold border border-white/10">
                {user?.first_name?.[0]}{user?.last_name?.[0]}
            </Link>
        </div>
      </header>

      {/* Mobile Bottom Nav */}
      <BottomNav />

      {/* Desktop Sidebar (Fixed) */}
      <aside 
        className="hidden lg:flex fixed inset-y-0 left-0 w-64 bg-[#002147] border-r border-white/5 z-[90] flex-col"
        style={{
          background: 'linear-gradient(180deg, #002147 0%, #001a38 100%)'
        }}
      >
        <SidebarContent />
      </aside>

      {/* Mobile Sidebar Overlay */}
      {mobileMenuOpen && (
        <div 
          className="lg:hidden fixed inset-0 bg-black/60 backdrop-blur-sm z-[110]"
          onClick={() => setMobileMenuOpen(false)}
        />
      )}

      {/* Mobile Sidebar Content */}
      <aside 
        className={`lg:hidden fixed inset-y-0 left-0 w-72 bg-[#002147] z-[120] transform transition-transform duration-300 ease-in-out shadow-2xl ${mobileMenuOpen ? 'translate-x-0' : '-translate-x-full'}`}
      >
        <SidebarContent />
      </aside>

      {/* Global CSS for Sidebar */}
      <style>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 4px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: transparent;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: rgba(255, 255, 255, 0.1);
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: rgba(255, 255, 255, 0.2);
        }
      `}</style>
    </>
  );
}