"use client";

import * as React from "react";
import { Settings, MessageCircleQuestion, Search, School, Users } from "lucide-react";
import Link from "next/link";

import { NavMain } from "@/app/(main)/dashboard/_components/sidebar/nav-main";
import { NavSecondary } from "@/app/(main)/dashboard/_components/sidebar/nav-secondary";
import { NavUser } from "@/app/(main)/dashboard/_components/sidebar/nav-user";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from "@/components/ui/sidebar";
import { sidebarItems } from "@/navigation/sidebar/sidebar-items";
import { useAuth } from "@/contexts/auth-context";
import { useSchool } from "@/hooks/use-school";

const navSecondaryData = [
  {
    title: "User Management",
    url: "/dashboard/users",
    icon: Users,
    roles: ["ADMIN"],
  },
  {
    title: "Setting Sekolah",
    url: "/dashboard/setting-sekolah",
    icon: Settings,
    roles: ["ADMIN"],
  },
];

export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
  const { user } = useAuth();
  const { school, isLoading } = useSchool();

  // Default fallback data
  const schoolName = school?.namaSekolah || "SISADIK";
  const userData = user
    ? {
        name: user.name || user.username || "User",
        email: user.email || user.username, // Use username if email is null
        avatar: "/avatars/default.jpg",
        role: user.role,
      }
    : {
        name: "User",
        email: "user@example.com",
        avatar: "/avatars/default.jpg",
        role: "USER" as const,
      };

  // Filter logic
  const filteredNavItems = React.useMemo(() => {
    if (!user) return [];

    return sidebarItems
      .map((group) => {
        const filteredItems = group.items.filter((item) => {
          // Filter subItems if they exist
          if (item.subItems) {
            item.subItems = item.subItems.filter((sub) => !sub.roles || sub.roles.includes(user.role));
          }

          // Return true if:
          // 1. Item has no roles defined (public)
          // 2. User has required role
          return !item.roles || item.roles.includes(user.role);
        });

        return { ...group, items: filteredItems };
      })
      .filter((group) => group.items.length > 0);
  }, [user]);

  // Filter Secondary Nav
  const filteredSecondaryNav = React.useMemo(() => {
    if (!user) return [];
    return navSecondaryData.filter((item) => !item.roles || item.roles.includes(user.role));
  }, [user]);

  return (
    <Sidebar collapsible="icon" {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton asChild className="data-[slot=sidebar-menu-button]:p-1.5!">
              <Link href="/dashboard">
                <School className="size-5!" />
                <span className="text-base font-semibold">{isLoading ? "Loading..." : schoolName}</span>
              </Link>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>
      <SidebarContent>
        <NavMain items={filteredNavItems} />
        <NavSecondary items={filteredSecondaryNav} className="mt-auto" />
      </SidebarContent>
      <SidebarFooter>
        <NavUser user={userData} />
      </SidebarFooter>
    </Sidebar>
  );
}
