'use client';

import * as React from 'react';
import { useSession } from 'next-auth/react';
import { IconDashboard, IconChartBar, IconFolder, IconSearch, IconShieldCheck } from '@tabler/icons-react';
import { NavMain } from '@/components/nav-main';
import { NavSecondary } from '@/components/nav-secondary';
import { NavUser } from '@/components/nav-user';
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from '@/components/ui/sidebar';

interface NavItem {
  title: string;
  url: string;
  icon?: any;
  items?: NavItem[];
}

const navMainBase: NavItem[] = [
  { title: 'Library', url: '/dashboard', icon: IconDashboard },
  { title: 'Liked Videos', url: '/dashboard/liked-videos', icon: IconChartBar },
  { title: 'History', url: '/dashboard/watch-history', icon: IconFolder },
];

const navSecondary = [
  { title: 'Search', url: '#', icon: IconSearch },
];

export function AppSidebar(props: React.ComponentProps<typeof Sidebar>) {
  const { data: session } = useSession();
  const role = (session as any)?.user?.role ?? 'user';

  // Compose navMain and optionally add admin link for admins or superadmins
  const navMain = React.useMemo(() => {
    const base = [...navMainBase];

    if (role === 'admin' || role === 'superadmin') {
      // Put Admin at the top with submenu items
      base.unshift({
        title: 'Admin',
        url: '/admin',
        icon: IconShieldCheck,
        // nested submenu items
        items: [
          { title: 'Manage Users', url: '/admin/users' },
          { title: 'Manage Enrollments', url: '/admin/enrollments' },
          { title: 'Manage Courses', url: '/admin/courses' },
          { title: 'Manage Playlists', url: '/admin/playlists' },
          { title: 'Manage Videos', url: '/admin/videos' },
        ],
      });
    }

    return base;
  }, [role]);

  const user = session?.user
    ? {
        name: session.user.name ?? 'User',
        email: session.user.email ?? '',
        avatar: session.user.image ?? '/avatars/shadcn.jpg',
      }
    : { name: 'Guest', email: 'guest@example.com', avatar: '/avatars/shadcn.jpg' };

  return (
    <Sidebar collapsible="offcanvas" {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton asChild className="data-[slot=sidebar-menu-button]:p-1.5!">
              <a href="/dashboard">
                <img src="/icon.svg" alt="" className="size-5" />
                <span className="text-base font-semibold">OW ANIMATION ARTS VAULT</span>
              </a>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>

      <SidebarContent>
        <NavMain items={navMain} />
        <NavSecondary items={navSecondary} className="mt-auto" />
      </SidebarContent>

      <SidebarFooter>
        <NavUser user={user} />
      </SidebarFooter>
    </Sidebar>
  );
}
