import { useQuery } from 'react-query';

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

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

import usePermissions from 'src/hooks/usePermissions';
import { documentsKeys } from 'src/pages/dashboard/documents/queries';
import { documentsSkeletonRoutes } from 'src/pages/dashboard/documents/routes';
import { getDocumentNotifications } from 'src/services/documents';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { ROUTE_PERMISSIONS } from 'src/utils/permissions';

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

const { key, titleTranslationKey } = itemsConfig.documents;

const PATH = documentsSkeletonRoutes.documents();
const REQUIRED_PERMISSIONS = ROUTE_PERMISSIONS.DOCUMENTS;

const NavDocumentsItem = (props: SidebarItemProps) => {
  const { isCollapsed, onClick, isActive: isActiveProp } = props;
  const { t } = useLokaliseTranslation('dashboard_sidebar_app');
  const { enqueueSnackbar } = useSnackbar();
  const { hasAny: hasPermissions } = usePermissions(REQUIRED_PERMISSIONS);

  const { data } = useQuery(
    documentsKeys.notifications.module(),
    () => getDocumentNotifications(),
    {
      onError: () => {
        enqueueSnackbar({
          title: t('general:error_loading_home_notifications'),
          variant: 'error',
        });
      },
      enabled: hasPermissions,
    },
  );

  const {
    pendingSignatureNotifications = 0,
    newSignatureNotNeededDocumentsNotifications = 0,
  } = data?.data || {};

  const documentNotifications =
    pendingSignatureNotifications + newSignatureNotNeededDocumentsNotifications;

  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconFileText,
    key: 'Personal documents',
  });

  const isActive = isActiveProp ?? getItemIsActive(PATH);

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

export default NavDocumentsItem;
