import { useQuery } from 'react-query';

import { IconNews } 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 { newsKeys } from 'src/pages/dashboard/news/queries';
import { newsRoutes } from 'src/pages/dashboard/news/routes';
import { getNewsNotifications } from 'src/services/news';
import { useLokaliseTranslation as useTranslation } 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.articles;

const PATH = newsRoutes.news();
const MODULE = 'ARTICLES';

const NavNewItem = (props: SidebarItemProps) => {
  const { isCollapsed = false, onClick, isActive: isActiveProp } = props;
  const showGeneralError = useGeneralError();

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

  const { t } = useTranslation();
  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconNews,
    key: 'Magazine',
  });

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

  const isActive = isActiveProp ?? getItemIsActive(PATH);

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

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

export default NavNewItem;
