import { useQuery } from 'react-query';

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

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

import useCustomServerTranslation from 'src/hooks/useCustomServerTranslation';
import useGeneralError from 'src/hooks/useGeneralError';
import { onBoardingKeys } from 'src/pages/dashboard/onboarding/queries';
import { onboardingRoutes } from 'src/pages/dashboard/onboarding/routes';
import { getOnboardingsNotifications } from 'src/services/onboarding';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

const NAMESPACE = 'ONBOARDINGS';

const { key, titleTranslationKey } = itemsConfig.onboardings;

const PATH = onboardingRoutes.all();

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

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

  const title = useCustomServerTranslation({
    module: NAMESPACE,
    defaultTranslationKey: titleTranslationKey,
    namespace: 'dashboard_sidebar_app',
  });

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

  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconDoor,
    key: 'Onboarding',
  });

  const isActive = isActiveProp ?? getItemIsActive(PATH);

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

export default NavOnBoardingItem;
