import { useLayout } from '@/context/layout-provider'
import { canAccess } from '@/lib/permissions'
import { useAuthStore } from '@/stores/auth-store'
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarRail,
} from '@/components/ui/sidebar'
// import { AppTitle } from './app-title'
import { sidebarData } from './data/sidebar-data'
import { NavGroup } from './nav-group'
import { NavUser } from './nav-user'
import { TeamSwitcher } from './team-switcher'
import { type NavGroup as NavGroupType, type NavItem } from './types'

function filterNavItem(
  item: NavItem,
  permissions: Record<string, string[]> | undefined
): NavItem | null {
  if (!canAccess(permissions, item.permission)) {
    return null
  }

  if (!item.items) {
    return item
  }

  const items = item.items.filter((subItem) =>
    canAccess(permissions, subItem.permission)
  )

  if (!items.length) {
    return null
  }

  return { ...item, items }
}

function filterNavGroups(
  groups: NavGroupType[],
  permissions: Record<string, string[]> | undefined
) {
  return groups
    .map((group) => ({
      ...group,
      items: group.items
        .map((item) => filterNavItem(item, permissions))
        .filter((item): item is NavItem => Boolean(item)),
    }))
    .filter((group) => group.items.length)
}

export function AppSidebar() {
  const { collapsible, variant } = useLayout()
  const permissions = useAuthStore((state) => state.auth.user?.permissions)
  const navGroups = filterNavGroups(sidebarData.navGroups, permissions)

  return (
    <Sidebar collapsible={collapsible} variant={variant}>
      <SidebarHeader>
        <TeamSwitcher teams={sidebarData.teams} />

        {/* Replace <TeamSwitch /> with the following <AppTitle />
         /* if you want to use the normal app title instead of TeamSwitch dropdown */}
        {/* <AppTitle /> */}
      </SidebarHeader>
      <SidebarContent>
        {navGroups.map((props) => (
          <NavGroup key={props.title} {...props} />
        ))}
      </SidebarContent>
      <SidebarFooter>
        <NavUser user={sidebarData.user} />
      </SidebarFooter>
      <SidebarRail />
    </Sidebar>
  )
}
