'use client'

import React from 'react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import Image from 'next/image'
import { cn } from '@/lib/utils'
import {
  LayoutDashboard,
  User,
  GraduationCap,
  FileBarChart,
  BookOpen,
  Calculator,
  Search,
  Trophy,
  HandCoins,
  Bot,
  Crown,
  LogOut,
  Users,
  Settings,
  CreditCard,
  Building2,
  X,
  Wrench,
} from 'lucide-react'
import { Sheet, SheetContent, SheetTitle } from '@/components/ui/sheet'

export type SidebarRole = 'student' | 'admin' | 'tutor'

interface SidebarMenuProps {
  role: SidebarRole
  activeItem: string
  userName: string
  userAvatar?: string
  userGrade?: number
  className?: string
}

interface MenuItem {
  label: string
  href: string
  icon: React.ElementType
  highlight?: boolean
}

const studentMenuItems = (userGrade?: number): MenuItem[] => [
  { label: 'Dashboard', href: '/dashboard', icon: LayoutDashboard },
  { label: 'My Profile', href: '/profile', icon: User },
  { label: 'Academic & Career', href: '/academic-career', icon: GraduationCap },
  { label: 'Full Analysis Report', href: '/analysis-report', icon: FileBarChart },
  { label: 'Academic Results', href: '/results', icon: BookOpen },
  ...(userGrade === 12 ? [{ label: 'APS Calculator', href: '/aps-calculator', icon: Calculator }] : []),
  { label: 'Find Tutors', href: '/tutors', icon: Search },
  { label: 'Competitions', href: '/competitions', icon: Trophy },
  { label: 'Bursary', href: '/bursary', icon: HandCoins },
  { label: 'Study Tools', href: '/study-tools', icon: Wrench },
  { label: 'AI Coach', href: '/ai-coach', icon: Bot, highlight: true },
  { label: 'Go Premium', href: '/premium', icon: Crown, highlight: true },
]

const adminMenuItems: MenuItem[] = [
  { label: 'Dashboard', href: '/admin', icon: LayoutDashboard },
  { label: 'Users', href: '/admin/users', icon: Users },
  { label: 'Tutors', href: '/admin/tutors', icon: GraduationCap },
  { label: 'Competitions', href: '/admin/competitions', icon: Trophy },
  { label: 'Payments', href: '/admin/payments', icon: CreditCard },
  { label: 'Sponsors', href: '/admin/sponsors', icon: Building2 },
  { label: 'Settings', href: '/admin/settings', icon: Settings },
]

function SidebarContent({
  role,
  activeItem,
  userName,
  userAvatar,
  userGrade,
  onNavigate,
}: SidebarMenuProps & { onNavigate?: () => void }) {
  const menuItems = role === 'admin' ? adminMenuItems : studentMenuItems(userGrade)

  return (
    <div className="flex h-full flex-col bg-[#2c3e50]">
      {/* Logo Section */}
      <div className="flex items-center gap-3 px-6 py-6">
        <div className="relative h-10 w-10 flex-shrink-0 overflow-hidden rounded-lg bg-white/10">
          <Image
            src="/images/logo.png"
            alt="Studo Guide"
            fill
            className="object-contain"
          />
        </div>
        <div>
          <h1 className="text-lg font-bold bg-gradient-to-r from-[#91C4D9] to-[#5b9ebd] bg-clip-text text-transparent">
            Studo Guide
          </h1>
          <p className="text-xs text-gray-400">Your Future Career Guide</p>
        </div>
      </div>

      {/* Welcome */}
      <div className="border-t border-white/10 px-6 py-4">
        <p className="text-sm text-gray-300">
          Welcome, <span className="font-semibold text-white">{userName}</span>!
        </p>
      </div>

      {/* Menu Items */}
      <nav className="flex-1 overflow-y-auto px-3 py-2">
        <ul className="space-y-1">
          {menuItems.map((item) => {
            const isActive = activeItem === item.href || activeItem?.startsWith(item.href + '/')
            const Icon = item.icon
            return (
              <li key={item.href}>
                <Link
                  href={item.href}
                  onClick={onNavigate}
                  className={cn(
                    'flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200',
                    isActive
                      ? 'border-l-[3px] border-[#91C4D9] bg-[#34495e] text-white'
                      : 'text-gray-300 hover:bg-[#34495e] hover:text-white border-l-[3px] border-transparent',
                    item.highlight && !isActive &&
                      'bg-gradient-to-r from-[#91C4D9]/20 to-[#5b9ebd]/20 text-[#91C4D9] hover:text-white'
                  )}
                >
                  <Icon className="h-5 w-5 flex-shrink-0" />
                  {item.label}
                </Link>
              </li>
            )
          })}
        </ul>
      </nav>

      {/* Logout */}
      <div className="border-t border-white/10 p-3">
        <Link
          href="/login"
          className="flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-red-300 transition-all hover:bg-red-500/10 hover:text-red-200"
        >
          <LogOut className="h-5 w-5 flex-shrink-0" />
          Logout
        </Link>
      </div>
    </div>
  )
}

export function Sidebar(props: SidebarMenuProps) {
  return (
    <>
      {/* Desktop Sidebar */}
      <aside className="fixed inset-y-0 left-0 z-40 hidden w-[260px] lg:block">
        <SidebarContent {...props} />
      </aside>
    </>
  )
}

export function MobileSidebar(props: SidebarMenuProps & { open: boolean; onOpenChange: (open: boolean) => void }) {
  return (
    <Sheet open={props.open} onOpenChange={props.onOpenChange}>
      <SheetContent side="left" className="w-[280px] p-0">
        <SheetTitle className="sr-only">Navigation Menu</SheetTitle>
        <SidebarContent {...props} onNavigate={() => props.onOpenChange(false)} />
      </SheetContent>
    </Sheet>
  )
}

export function useSidebarActiveItem(): string {
  const pathname = usePathname()
  return pathname
}
