"use client"

import * as React from "react"
import { useSession } from "next-auth/react"
import {
  BookOpen,
  Calendar,
  GraduationCap,
  Home,
  Settings,
  Users,
  BarChart3,
  ClipboardList,
  UserCheck,
  UserPlus,
  School,
  Download,
} from "lucide-react"

import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarRail,
} from "@/components/ui/sidebar"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { signOut } from "next-auth/react"
import Link from "next/link"
import { ModeToggle } from "@/components/mode-toggle"

// Menú para Administrador - Agrupado por secciones
const adminMenuSections = [
  {
    label: "Principal",
    items: [
      {
        title: "Dashboard",
        url: "/admin/dashboard",
        icon: Home,
      },
    ],
  },
  {
    label: "Gestión de Usuarios",
    items: [
      {
        title: "Profesores",
        url: "/admin/teachers",
        icon: Users,
      },
      {
        title: "Estudiantes",
        url: "/admin/students",
        icon: GraduationCap,
      },
    ],
  },
  {
    label: "Gestión Académica",
    items: [
      {
        title: "Períodos Académicos",
        url: "/admin/periods",
        icon: Calendar,
      },
      {
        title: "Clases",
        url: "/admin/classes",
        icon: BookOpen,
      },
      {
        title: "Secciones",
        url: "/admin/sections",
        icon: School,
      },
    ],
  },
  {
    label: "Asignaciones e Inscripciones",
    items: [
      {
        title: "Asignaciones de Profesores",
        url: "/admin/teacher-assignments",
        icon: UserCheck,
      },
      {
        title: "Inscripciones de Estudiantes",
        url: "/admin/student-enrollments",
        icon: UserPlus,
      },
      {
        title: "Historial de Inscripciones",
        url: "/admin/enrollment-history",
        icon: BarChart3,
      },
    ],
  },
  {
    label: "Configuración",
    items: [
      {
        title: "Parciales",
        url: "/admin/partials",
        icon: Settings,
      },
    ],
  },
]

// Menú para Profesor - Agrupado por secciones
const teacherMenuSections = [
  {
    label: "Principal",
    items: [
      {
        title: "Dashboard",
        url: "/teacher",
        icon: Home,
      },
      {
        title: "Estudiantes",
        url: "/teacher/students",
        icon: GraduationCap,
      },
    ],
  },
  {
    label: "Gestión de Asistencia",
    items: [
      {
        title: "Tomar Asistencia",
        url: "/teacher/attendance",
        icon: UserCheck,
      },
      {
        title: "Historial de Asistencia",
        url: "/teacher/attendance-history",
        icon: ClipboardList,
      },
      // {
      //   title: "Asistencia por Estudiante",
      //   url: "/teacher/student-attendance",
      //   icon: Users,
      // },
    ],
  },
  {
    label: "Reportes",
    items: [
      {
        title: "Exportar Reportes",
        url: "/teacher/export-reports",
        icon: Download,
      },
    ],
  },
]

// Menú para Estudiante - Agrupado por secciones
const studentMenuSections = [
  {
    label: "Principal",
    items: [
      {
        title: "Dashboard",
        url: "/student/dashboard",
        icon: Home,
      },
    ],
  },
  {
    label: "Académico",
    items: [
      {
        title: "Mis Clases",
        url: "/student/classes",
        icon: BookOpen,
      },
      {
        title: "Horarios",
        url: "/student/schedule",
        icon: Calendar,
      },
    ],
  },
  {
    label: "Asistencia",
    items: [
      {
        title: "Mi Asistencia",
        url: "/student/attendance",
        icon: ClipboardList,
      },
    ],
  },
]

export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
  const { data: session, status } = useSession()

  if (status === "loading") {
    return null
  }

  if (!session?.user) {
    return null
  }

  const isAdmin = session.user.role === "admin"
  const isTeacher = session.user.role === "teacher"
  const isStudent = session.user.role === "student"
  const menuSections = isAdmin ? adminMenuSections : isTeacher ? teacherMenuSections : studentMenuSections
  const userInitials = session.user.firstName?.[0] + (session.user.lastName?.[0] || "")

  return (
    <Sidebar collapsible="icon" {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton size="lg" asChild>
              <Link href={isAdmin ? "/admin/dashboard" : isTeacher ? "/teacher/dashboard" : "/student/dashboard"}>
                <div className="flex aspect-square size-8 items-center justify-center rounded-lg bg-sidebar-primary text-sidebar-primary-foreground">
                  <School className="size-4" />
                </div>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-semibold">Sistema de Asistencia</span>
                  <span className="truncate text-xs">
                    {isAdmin ? "Administrador" : isTeacher ? "Profesor" : "Estudiante"}
                  </span>
                </div>
              </Link>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>

      <SidebarContent>
        {menuSections.map((section) => (
          <SidebarGroup key={section.label}>
            <SidebarGroupLabel>{section.label}</SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu>
                {section.items.map((item) => (
                  <SidebarMenuItem key={item.title}>
                    <SidebarMenuButton asChild>
                      <Link href={item.url}>
                        <item.icon />
                        <span>{item.title}</span>
                      </Link>
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                ))}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        ))}
      </SidebarContent>

      <SidebarFooter>
        <SidebarMenuItem>
          <div className="flex items-center gap-2 px-2 py-1.5">
            <ModeToggle />
          </div>
        </SidebarMenuItem>
        <SidebarMenu>
          <SidebarMenuItem>
            <div className="flex items-center gap-2 px-2 py-1.5">
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-semibold">
                  {session.user.firstName} {session.user.lastName}
                </span>
                <span className="truncate text-xs text-muted-foreground">
                  {session.user.email}
                </span>
              </div>
            </div>
          </SidebarMenuItem>
          <SidebarMenuItem>
            <Button
              variant="ghost"
              size="sm"
              className="w-full justify-start"
              onClick={() => signOut({ callbackUrl: "/" })}
            >
              Cerrar Sesión
            </Button>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarFooter>

      <SidebarRail />
    </Sidebar>
  )
}