import { useQuery } from 'react-query';

import { IconShoppingBag } from '@material-hu/icons/tabler';

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

import useGeneralError from 'src/hooks/useGeneralError';
import { marketplaceKeys } from 'src/pages/dashboard/marketplace/queries';
import { marketplaceRoutes } from 'src/pages/dashboard/marketplace/routes';
import { getMarketplaceNotifications } from 'src/services/marketplace';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

const { key, titleTranslationKey } = itemsConfig.marketplace;

const PATH = marketplaceRoutes.marketplace();

const NavMarketplaceItem = (props: SidebarItemProps) => {
  const { isCollapsed, onClick, isActive: isActiveProp } = props;
  const { t } = useLokaliseTranslation('dashboard_sidebar_app');
  const showGeneralError = useGeneralError();

  const { data } = useQuery(
    marketplaceKeys.notifications.module(),
    () => getMarketplaceNotifications(),
    {
      onError: err => {
        showGeneralError(err, t('general:error_loading_home_notifications'));
      },
    },
  );

  const { marketplaceNotifications = 0 } = data?.data || {};

  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconShoppingBag,
    key: 'Marketplace',
  });

  const isActive = isActiveProp ?? getItemIsActive(PATH);

  return (
    <HuSidebarNavItem
      key={key}
      depth={0}
      title={t(titleTranslationKey)}
      icon={<Icon />}
      path={PATH}
      info={{
        notificationCount: marketplaceNotifications,
      }}
      isCollapsed={isCollapsed}
      onClick={onClick}
      active={isActive}
    />
  );
};

export default NavMarketplaceItem;
