import { useQuery } from 'react-query';

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

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

import useGeneralError from 'src/hooks/useGeneralError';
import { performanceKeys } from 'src/pages/dashboard/performance/queries';
import { performanceRoutes } from 'src/pages/dashboard/performance/routes';
import { getPerformanceNotifications } from 'src/pages/dashboard/performance/services';
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.performanceReviews;

const PATH = performanceRoutes.performance();

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

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

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

  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconRocket,
    key: 'Performance',
  });

  const isActive = isActiveProp ?? getItemIsActive(PATH);

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

export default NavPerformanceItem;
