import { IconTrophy } from '@material-hu/icons/tabler';
import { useQuery } from 'react-query';

import HuSidebarNavItem from '@material-hu/components/design-system/Sidebar/components/NavItem';

import { useAuth } from 'src/contexts/JWTContext';
import { getProdeAccess, prodeKeys } from 'src/services/prode';
import { sportsPoolRoutes } from 'src/pages/dashboard/sportsPool/routes';
import { useLokaliseTranslation } from 'src/utils/i18n';

import itemsConfig from '../constants';
import { SidebarItemProps } from '../types';
import { getItemIsActive } from '../utils';

const PATH = sportsPoolRoutes.competitions();
const { key, titleTranslationKey } = itemsConfig.sportsPool;

const NavSportsPoolItem = ({
  isCollapsed,
  onClick,
  isActive: isActiveProp,
}: SidebarItemProps) => {
  const { user } = useAuth();
  const { t } = useLokaliseTranslation('dashboard_sidebar_app');

  // Fetch access data to get custom module name and check if user has competitions
  const {
    data: accessData,
    isLoading,
    isError,
  } = useQuery(prodeKeys.access(), () => getProdeAccess(), {
    enabled: !!user,
    staleTime: 1000 * 60 * 5, // Cache for 5 minutes
    select: res => res.data,
    retry: 1,
  });

  const isActive = isActiveProp ?? getItemIsActive(PATH);

  // Don't render if:
  // - Still loading
  // - Error fetching access
  // - No access granted
  // - No competitions assigned to user
  if (
    isLoading ||
    isError ||
    !accessData?.hasAccess ||
    !accessData?.hasAssignedCompetitions
  ) {
    return null;
  }

  // Use custom module name from backend or fallback to translation
  const title = accessData.moduleName || t(titleTranslationKey);

  return (
    <HuSidebarNavItem
      key={key}
      depth={0}
      title={title}
      icon={<IconTrophy />}
      path={PATH}
      isCollapsed={isCollapsed}
      onClick={onClick}
      active={isActive}
    />
  );
};

export default NavSportsPoolItem;
