'use client';

import { useMemo } from 'react';
import { useSession } from 'next-auth/react';
import type { NavGroup, NavItem } from '@/types';

function canAccessItem(
  item: NavItem,
  accessContext: {
    hasOrg: boolean;
    systemRole: string | null | undefined;
    activeMembershipRole: string | null | undefined;
    activePermissions: string[];
  }
) {
  if (!item.access) {
    return true;
  }

  if (item.access.systemRole && accessContext.systemRole !== item.access.systemRole) {
    return false;
  }

  if (item.access.requireOrg && !accessContext.hasOrg) {
    return false;
  }

  if (accessContext.systemRole === 'super_admin') {
    return true;
  }

  if (item.access.permission) {
    if (!accessContext.hasOrg || !accessContext.activePermissions.includes(item.access.permission)) {
      return false;
    }
  }

  if (item.access.role) {
    if (!accessContext.hasOrg || accessContext.activeMembershipRole !== item.access.role) {
      return false;
    }
  }

  if (item.access.plan || item.access.feature) {
    console.warn(
      `Plan/feature checks for navigation items require server-side verification. ` +
        `Item "${item.title}" will be shown, but page-level protection should be implemented.`
    );
  }

  return true;
}

export function useFilteredNavItems(items: NavItem[]) {
  const { data: session } = useSession();

  const accessContext = useMemo(
    () => ({
      hasOrg: !!session?.user?.activeOrganizationId,
      systemRole: session?.user?.systemRole,
      activeMembershipRole: session?.user?.activeMembershipRole,
      activePermissions: session?.user?.activePermissions ?? []
    }),
    [
      session?.user?.activeOrganizationId,
      session?.user?.activePermissions,
      session?.user?.activeMembershipRole,
      session?.user?.systemRole
    ]
  );

  return useMemo(() => {
    return items
      .filter((item) => canAccessItem(item, accessContext))
      .map((item) => {
        if (!item.items?.length) {
          return item;
        }

        return {
          ...item,
          items: item.items.filter((childItem) => canAccessItem(childItem, accessContext))
        };
      });
  }, [accessContext, items]);
}

export function useFilteredNavGroups(groups: NavGroup[]) {
  const allItems = useMemo(() => groups.flatMap((group) => group.items), [groups]);
  const filteredItems = useFilteredNavItems(allItems);

  return useMemo(() => {
    const filteredSet = new Set(filteredItems.map((item) => item.title));

    return groups
      .map((group) => ({
        ...group,
        items: filteredItems.filter((item) =>
          group.items.some((groupItem) => groupItem.title === item.title && filteredSet.has(groupItem.title))
        )
      }))
      .filter((group) => group.items.length > 0);
  }, [filteredItems, groups]);
}
