import { useQuery } from 'react-query';

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

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

import useGeneralError from 'src/hooks/useGeneralError';
import { getFormChatsNotifications } from 'src/services/forms';
import { FormType } from 'src/types/forms';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { formKeys } from 'src/components/dashboard/form/queries';
import { formRoutes } from 'src/components/dashboard/form/routes';

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

const { key, titleTranslationKey } = itemsConfig.forms;

const PATH = formRoutes.forms(FormType.FORM);

const NavFormsItem = (props: SidebarItemProps) => {
  const { isCollapsed, onClick, isActive: isActiveProp } = props;
  const { t } = useLokaliseTranslation('dashboard_sidebar_app');
  const showGeneralError = useGeneralError();
  const { data } = useQuery(
    formKeys.notifications.module(),
    () => getFormChatsNotifications(),
    {
      onError: err => {
        showGeneralError(err, t('general:error_loading_home_notifications'));
      },
    },
  );

  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconChecklist,
    key: 'Forms & Tasks',
  });

  const {
    unreadUserFormChatNotifications = 0,
    unreadAgentFormChatNotifications = 0,
  } = data?.data || {};

  const formNotifications =
    unreadUserFormChatNotifications + unreadAgentFormChatNotifications;

  const isActive = isActiveProp ?? getItemIsActive(PATH);

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

export default NavFormsItem;
