import { useQuery } from 'react-query';

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

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

import useGeneralError from 'src/hooks/useGeneralError';
import { surveysRoutes } from 'src/pages/dashboard/surveys/routes';
import { getSurveysNotifications } from 'src/services/surveys';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { surveyKeys } from 'src/components/dashboard/surveys/queries';

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

const { key, titleTranslationKey } = itemsConfig.surveys;

const PATH = surveysRoutes.base();

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

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

  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconCheckupList,
    key: 'Surveys',
  });

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

  const isActive = isActiveProp ?? getItemIsActive(PATH);

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

export default NavSurveysItem;
