import { useMemo } from 'react';
import { useQuery } from 'react-query';

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

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

import useGeneralError from 'src/hooks/useGeneralError';
import usePermissions from 'src/hooks/usePermissions';
import useConversationsEvents from 'src/pages/dashboard/Conversations/hooks/useConversationsEvents';
import { useGetUnreadChannels } from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import { conversationsSkeletonRoutes } from 'src/pages/dashboard/Conversations/routes';
import { getChatsNotifications } from 'src/services/chats';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';

import { chatSkeletonRoutes } from 'src/components/dashboard/chat/routes';

import { chatKeys } from '../../chat/queries';
import useGetSidebarIcon from '../hooks/useSidebarIcon';
import { type SidebarItemProps } from '../types';
import { getConversationsModuleName, getItemIsActive } from '../utils';

const PATH_CHAT = chatSkeletonRoutes.chats();
const PATH_CONVERSATIONS = conversationsSkeletonRoutes.conversations();

const { VIEW_REGULAR_CHATS, VIEW_TICKETS, VIEW_CHATS_V2 } = UserPermissions;

const NavChatsItem = (props: SidebarItemProps) => {
  const { isCollapsed = false, onClick, isActive: isActiveProp } = props;
  const { t } = useLokaliseTranslation('dashboard_sidebar_app');
  const showGeneralError = useGeneralError();
  const { hasAll: canViewChats } = usePermissions([VIEW_REGULAR_CHATS]);
  const { hasAll: canViewConversations } = usePermissions([VIEW_CHATS_V2]);
  const { hasAll: canViewTickets } = usePermissions([VIEW_TICKETS]);
  useConversationsEvents();

  const { data: conversationData } = useGetUnreadChannels({
    enabled: canViewConversations,
  });

  const { data: chatData } = useQuery(
    chatKeys.notifications.module(),
    () => getChatsNotifications(),
    {
      onError: err => {
        showGeneralError(err, t('general:error_loading_home_notifications'));
      },
      enabled: !canViewConversations,
    },
  );

  const chatNotifications = useMemo(() => {
    if (!canViewConversations && chatData) {
      const { agentChatNotifications, userChatNotifications } = chatData.data;
      return agentChatNotifications + userChatNotifications;
    }
    return conversationData;
  }, [
    chatData,
    conversationData,
    chatData?.data.userChatNotifications,
    chatData?.data.agentChatNotifications,
  ]);

  const { Icon } = useGetSidebarIcon({
    defaultIcon: IconMessages,
    key: 'Chats',
  });

  const PATH = canViewConversations ? PATH_CONVERSATIONS : PATH_CHAT;
  const isActive = isActiveProp ?? getItemIsActive(PATH);

  return (
    <HuSidebarNavItem
      key="chats"
      depth={0}
      title={t(
        getConversationsModuleName({
          canViewTickets,
          canViewConversations,
          canViewChats,
        }),
      )}
      icon={<Icon />}
      path={PATH}
      info={{
        notificationCount: chatNotifications,
      }}
      isCollapsed={isCollapsed}
      onClick={onClick}
      active={isActive}
    />
  );
};

export default NavChatsItem;
