"use client";

import * as React from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import Image from "next/image";
import { AuthSession } from "@/types";
import { cn } from "@/lib/utils";
import {
  LayoutDashboard,
  CalendarDays,
  Users,
  BookOpen,
  GraduationCap,
  ClipboardList,
  FileCheck,
  Award,
  Bell,
  Clock,
  Settings,
  LogOut,
  Calendar,
  FileSpreadsheet,
  Activity,
  Layers,
  ChevronLeft,
  ChevronRight,
  ShieldAlert,
} from "lucide-react";

interface SidebarProps {
  user: AuthSession;
  collapsed: boolean;
  onToggleCollapse: () => void;
  mobileOpen: boolean;
  onCloseMobile: () => void;
}

export function Sidebar({
  user,
  collapsed,
  onToggleCollapse,
  mobileOpen,
  onCloseMobile,
}: SidebarProps) {
  const pathname = usePathname();

  const getNavSections = () => {
    if (user.role === "ADMIN") {
      return [
        {
          title: "Menu Utama",
          items: [
            { label: "Dashboard", href: "/admin/dashboard", icon: LayoutDashboard },
          ],
        },
        {
          title: "Akademik",
          items: [
            { label: "Tahun Ajaran & Semester", href: "/admin/academic-years", icon: CalendarDays },
            { label: "Tingkat & Kelas", href: "/admin/classes", icon: Layers },
            { label: "Mata Pelajaran", href: "/admin/subjects", icon: BookOpen },
            { label: "Jadwal Pelajaran", href: "/admin/schedules", icon: Clock },
          ],
        },
        {
          title: "Pengguna",
          items: [
            { label: "Manajemen Pengguna", href: "/admin/users", icon: Users },
          ],
        },
        {
          title: "Informasi & Laporan",
          items: [
            { label: "Pengumuman", href: "/admin/announcements", icon: Bell },
            { label: "Kalender Akademik", href: "/admin/calendar", icon: Calendar },
            { label: "Rekap & Ekspor", href: "/admin/reports", icon: FileSpreadsheet },
            { label: "Audit Log", href: "/admin/audit-logs", icon: Activity },
          ],
        },
      ];
    }

    if (user.role === "TEACHER") {
      const teacherSections = [
        {
          title: "Menu Guru",
          items: [
            { label: "Dashboard", href: "/teacher/dashboard", icon: LayoutDashboard },
          ],
        },
        {
          title: "Pembelajaran",
          items: [
            { label: "Kelas Diajar", href: "/teacher/classes", icon: Layers },
            { label: "Materi Pembelajaran", href: "/teacher/materials", icon: BookOpen },
            { label: "Tugas Siswa", href: "/teacher/assignments", icon: ClipboardList },
            { label: "Kuis & Ujian (CBT)", href: "/teacher/quizzes", icon: FileCheck },
            { label: "Presensi Pertemuan", href: "/teacher/attendance", icon: Users },
            { label: "Buku Nilai (Gradebook)", href: "/teacher/gradebook", icon: Award },
            { label: "Jadwal Mengajar", href: "/teacher/schedules", icon: Clock },
            { label: "Pengumuman", href: "/teacher/announcements", icon: Bell },
          ],
        },
      ];

      if (user.isHomeroom) {
        teacherSections.push({
          title: "Wali Kelas",
          items: [
            { label: "Dashboard Wali Kelas", href: "/homeroom/dashboard", icon: GraduationCap },
            { label: "Daftar Siswa Binaan", href: "/homeroom/students", icon: Users },
            { label: "Buku Nilai Kelas", href: "/homeroom/grades", icon: Award },
            { label: "Cetak Rapor Siswa", href: "/homeroom/report", icon: FileSpreadsheet },
            { label: "Rekap Presensi", href: "/homeroom/attendance", icon: Calendar },
          ],
        });
      }

      return teacherSections;
    }

    // Default: STUDENT
    return [
      {
        title: "Menu Siswa",
        items: [
          { label: "Dashboard", href: "/student/dashboard", icon: LayoutDashboard },
        ],
      },
      {
        title: "Pembelajaran Digital",
        items: [
          { label: "Mata Pelajaran", href: "/student/subjects", icon: BookOpen },
          { label: "Materi Belajar", href: "/student/materials", icon: Layers },
          { label: "Tugas Saya", href: "/student/assignments", icon: ClipboardList },
          { label: "Kuis & Ujian (CBT)", href: "/student/quizzes", icon: FileCheck },
          { label: "Nilai Akademik", href: "/student/grades", icon: Award },
          { label: "Presensi Kehadiran", href: "/student/attendance", icon: Users },
          { label: "Jadwal Pelajaran", href: "/student/schedules", icon: Clock },
          { label: "Kalender Akademik", href: "/student/calendar", icon: Calendar },
          { label: "Pengumuman", href: "/student/announcements", icon: Bell },
        ],
      },
    ];
  };

  const sections = getNavSections();

  return (
    <>
      {/* Mobile overlay */}
      {mobileOpen && (
        <div
          onClick={onCloseMobile}
          className="fixed inset-0 z-40 bg-slate-900/60 backdrop-blur-sm md:hidden"
        />
      )}

      {/* Sidebar container */}
      <aside
        className={cn(
          "fixed top-0 left-0 z-40 h-screen bg-slate-900 text-slate-300 transition-all duration-300 flex flex-col border-r border-slate-800",
          collapsed ? "w-20" : "w-64",
          mobileOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"
        )}
      >
        {/* Header Branding */}
        <div className="flex h-16 items-center justify-between px-4 border-b border-slate-800 shrink-0">
          <Link
            href="/"
            className="flex items-center gap-3 overflow-hidden"
            onClick={onCloseMobile}
          >
            <div className="relative h-10 w-10 shrink-0 rounded-xl bg-blue-950 p-1 flex items-center justify-center border border-blue-800/80 shadow-md">
              <img
                src="/images/logo-sman3oku.svg"
                alt="SMAN 3 OKU"
                className="h-8 w-8 object-contain"
              />
            </div>
            {!collapsed && (
              <div className="flex flex-col truncate">
                <span className="text-sm font-extrabold text-white tracking-wide">
                  LMS SMAN 3 OKU
                </span>
                <span className="text-[10px] text-blue-400 font-medium truncate">
                  Digital Learning
                </span>
              </div>
            )}
          </Link>

          <button
            onClick={onToggleCollapse}
            className="hidden md:flex h-7 w-7 items-center justify-center rounded-lg bg-slate-800 text-slate-400 hover:text-white hover:bg-slate-700 transition-colors"
          >
            {collapsed ? <ChevronRight className="h-4 w-4" /> : <ChevronLeft className="h-4 w-4" />}
          </button>
        </div>

        {/* User Quick Info */}
        {!collapsed ? (
          <div className="px-4 py-3 border-b border-slate-800/80 bg-slate-950/40">
            <div className="flex items-center gap-3">
              <div className="h-9 w-9 rounded-full bg-blue-600/30 border border-blue-500/40 flex items-center justify-center text-xs font-bold text-blue-300 shrink-0">
                {user.fullName.substring(0, 2).toUpperCase()}
              </div>
              <div className="overflow-hidden">
                <p className="text-xs font-semibold text-white truncate">
                  {user.fullName}
                </p>
                <div className="flex items-center gap-1.5 mt-0.5">
                  <span className="inline-block h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse" />
                  <span className="text-[10px] font-medium text-slate-400">
                    {user.role === "ADMIN"
                      ? "Administrator"
                      : user.role === "TEACHER"
                      ? user.isHomeroom
                        ? "Guru & Wali Kelas"
                        : "Guru Pengampu"
                      : `Siswa (${user.className || "X.1"})`}
                  </span>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div className="py-3 flex justify-center border-b border-slate-800">
            <div className="h-8 w-8 rounded-full bg-blue-600/30 border border-blue-500/40 flex items-center justify-center text-xs font-bold text-blue-300">
              {user.fullName.substring(0, 1).toUpperCase()}
            </div>
          </div>
        )}

        {/* Nav Links */}
        <nav className="flex-1 overflow-y-auto px-3 py-4 space-y-6">
          {sections.map((section, idx) => (
            <div key={idx} className="space-y-1">
              {!collapsed && (
                <p className="px-3 text-[10px] font-bold uppercase tracking-wider text-slate-500">
                  {section.title}
                </p>
              )}
              <div className="space-y-0.5">
                {section.items.map((item) => {
                  const Icon = item.icon;
                  const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      onClick={onCloseMobile}
                      className={cn(
                        "flex items-center gap-3 rounded-xl px-3 py-2 text-xs font-medium transition-all group",
                        isActive
                          ? "bg-blue-600 text-white shadow-md shadow-blue-900/30 font-semibold"
                          : "text-slate-400 hover:bg-slate-800 hover:text-slate-200"
                      )}
                      title={collapsed ? item.label : undefined}
                    >
                      <Icon
                        className={cn(
                          "h-4 w-4 shrink-0 transition-colors",
                          isActive ? "text-white" : "text-slate-400 group-hover:text-slate-200"
                        )}
                      />
                      {!collapsed && <span className="truncate">{item.label}</span>}
                    </Link>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>

        {/* Footer actions */}
        <div className="p-3 border-t border-slate-800 space-y-1 shrink-0 bg-slate-950/40">
          <Link
            href="/profile"
            onClick={onCloseMobile}
            className={cn(
              "flex items-center gap-3 rounded-xl px-3 py-2 text-xs font-medium text-slate-400 hover:bg-slate-800 hover:text-slate-200 transition-colors"
            )}
            title={collapsed ? "Profil & Akun" : undefined}
          >
            <Settings className="h-4 w-4 shrink-0" />
            {!collapsed && <span>Profil & Akun</span>}
          </Link>

          <button
            onClick={async () => {
              await fetch("/api/auth/logout", { method: "POST" });
              window.location.href = "/login";
            }}
            className="w-full flex items-center gap-3 rounded-xl px-3 py-2 text-xs font-medium text-rose-400 hover:bg-rose-950/40 hover:text-rose-300 transition-colors text-left"
            title={collapsed ? "Keluar Sistem" : undefined}
          >
            <LogOut className="h-4 w-4 shrink-0" />
            {!collapsed && <span>Keluar Sistem</span>}
          </button>
        </div>
      </aside>
    </>
  );
}
