'use client'

import { useState } from 'react'
import { useSession, signOut } from 'next-auth/react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet'
import { Separator } from '@/components/ui/separator'
import {
  Menu,
  Home,
  Users,
  BookOpen,
  Calendar,
  ClipboardList,
  Settings,
  LogOut,
  GraduationCap,
  UserCheck,
  BarChart3,
  School,
  User,
  Layers
} from 'lucide-react'

interface SidebarProps {
  className?: string
}

const adminMenuItems = [
  { icon: Home, label: 'Dashboard', href: '/admin' },
  { icon: Users, label: 'Usuarios', href: '/admin/users' },
  { icon: School, label: 'Periodos', href: '/admin/periods' },
  { icon: BookOpen, label: 'Clases', href: '/admin/classes' },
  { icon: Layers, label: 'Secciones', href: '/admin/sections' },
  { icon: GraduationCap, label: 'Profesores', href: '/admin/teacher-assignments' },
  { icon: User, label: 'Estudiantes', href: '/admin/student-enrollments' },
  { icon: BarChart3, label: 'Reportes', href: '/admin/reports' },
  // { icon: Settings, label: 'Configuración', href: '/admin/settings' },
]

const teacherMenuItems = [
  { icon: Home, label: 'Dashboard', href: '/teacher' },
  { icon: BookOpen, label: 'Mis Clases', href: '/teacher/assignments' },
  { icon: UserCheck, label: 'Asistencia', href: '/teacher/attendance' },
  { icon: ClipboardList, label: 'Reportes', href: '/teacher/reports' },
  // { icon: Settings, label: 'Perfil', href: '/teacher/profile' },
]

const studentMenuItems = [
  { icon: Home, label: 'Dashboard', href: '/student' },
  { icon: BookOpen, label: 'Mis Clases', href: '/student/classes' },
  { icon: Calendar, label: 'Horarios', href: '/student/schedule' },
  { icon: ClipboardList, label: 'Mi Asistencia', href: '/student/attendance' },
  { icon: Settings, label: 'Perfil', href: '/student/profile' },
]

function SidebarContent({ className }: SidebarProps) {
  const { data: session } = useSession()
  const pathname = usePathname()

  const getMenuItems = () => {
    switch (session?.user?.role) {
      case 'ADMIN':
        return adminMenuItems
      case 'TEACHER':
        return teacherMenuItems
      case 'STUDENT':
        return studentMenuItems
      default:
        return []
    }
  }

  const menuItems = getMenuItems()

  const handleSignOut = () => {
    signOut({ callbackUrl: '/auth/signin' })
  }

  return (
    <div className={cn('flex h-full flex-col bg-white border-r', className)}>
      {/* Header */}
      <div className="p-6">
        <div className="flex items-center gap-2">
          <GraduationCap className="h-8 w-8 text-blue-600" />
          <div>
            <h1 className="text-xl font-bold text-gray-900">TAPIR</h1>
            <p className="text-sm text-gray-500">Sistema de Asistencia</p>
          </div>
        </div>
      </div>

      <Separator />

      {/* User Info */}
      {session?.user && (
        <div className="p-4">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-full bg-blue-100 flex items-center justify-center">
              <User className="h-5 w-5 text-blue-600" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-gray-900 truncate">
                {session.user.name || session.user.email}
              </p>
              <p className="text-xs text-gray-500 capitalize">
                {session.user.role?.toLowerCase()}
              </p>
            </div>
          </div>
        </div>
      )}

      <Separator />

      {/* Navigation */}
      <nav className="flex-1 p-4 space-y-1">
        {menuItems.map((item) => {
          const Icon = item.icon
          const isActive = pathname === item.href
          
          return (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                'flex items-center gap-3 px-3 py-2 text-sm font-medium rounded-md transition-colors',
                isActive
                  ? 'bg-blue-100 text-blue-700'
                  : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
              )}
            >
              <Icon className="h-5 w-5" />
              {item.label}
            </Link>
          )
        })}
      </nav>

      {/* Footer */}
      <div className="p-4">
        <Separator className="mb-4" />
        <Button
          variant="ghost"
          className="w-full justify-start text-gray-600 hover:text-gray-900 hover:bg-gray-100"
          onClick={handleSignOut}
        >
          <LogOut className="h-5 w-5 mr-3" />
          Cerrar Sesión
        </Button>
      </div>
    </div>
  )
}

export function Sidebar({ className }: SidebarProps) {
  return (
    <div className={cn('hidden lg:flex lg:w-64 lg:flex-col lg:fixed lg:inset-y-0', className)}>
      <SidebarContent />
    </div>
  )
}

export function MobileSidebar() {
  const [open, setOpen] = useState(false)

  return (
    <Sheet open={open} onOpenChange={setOpen}>
      <SheetTrigger asChild>
        <Button variant="ghost" size="icon" className="lg:hidden">
          <Menu className="h-6 w-6" />
        </Button>
      </SheetTrigger>
      <SheetContent side="left" className="p-0 w-64">
        <SidebarContent />
      </SheetContent>
    </Sheet>
  )
}