import { FC, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { Outlet, matchPath } from 'react-router-dom';

import 'src/components/dashboard/chat/i18n';
import 'src/pages/dashboard/tickets/i18n';

import Box from '@material-hu/mui/Box';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';
import useMediaQuery from '@material-hu/mui/useMediaQuery';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';
import useChatThread from 'src/pages/dashboard/chats/useChatThread';
import { getChatModuleName } from 'src/utils/chats';
import { formatTitle } from 'src/utils/helmetUtils';

import ArchiveChatButton from 'src/components/dashboard/chat/ArchiveChatButton';
import ChatsSidebar from 'src/components/dashboard/chat/ChatsSidebar';
import NewMenu from 'src/components/dashboard/chat/NewMenu';
import NewTickets from 'src/components/dashboard/chat/NewTickets';
import {
  refetchListChats,
  refetchArchiveListChats,
} from 'src/components/dashboard/chat/queries';
import { chatSkeletonRoutes } from 'src/components/dashboard/chat/routes';
import ThreadList from 'src/components/dashboard/chat/ThreadList';
import SearchBar from 'src/components/search/SearchBar';

const PATH_CHAT_THREAD = chatSkeletonRoutes.thread.detail();

const Chats: FC = () => {
  const socket = useSocket();

  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const {
    setQuery,
    chatsToShow,
    emptyInbox,
    dataArchivedCount,
    agentStats,
    query,
    queryClient,
    canViewChats,
    canViewConversations,
    canViewTickets,
    showArchived,
    setShowArchived,
    t,
  } = useChatThread();

  const handleChange = (value): void => setQuery(value);

  const { isResponsible = false, amountOfTicketsWhichNeedAttention = 0 } =
    agentStats?.data || {};

  useEffect(() => {
    const refetchChats = () => {
      refetchArchiveListChats();
      refetchListChats();
    };

    socket.listenEvent(EVENTS_SOCKETS.CHAT_ARCHIVED, refetchChats);

    socket.listenEvent(EVENTS_SOCKETS.CHAT_UNARCHIVED, refetchChats);

    return () => {
      socket.closeEvent(EVENTS_SOCKETS.CHAT_ARCHIVED, refetchChats);

      socket.closeEvent(EVENTS_SOCKETS.CHAT_UNARCHIVED, refetchChats);
    };
  }, [socket, queryClient]);

  const handleGoBack = () => setShowArchived(false);

  const isChatThread = !!matchPath(
    {
      path: PATH_CHAT_THREAD,
      end: false,
    },
    location.pathname,
  );

  const hideSidebar = isMobile && isChatThread;

  const showChat = !isMobile || isChatThread;

  return (
    <>
      <Helmet>
        <title>
          {formatTitle(
            getChatModuleName(
              canViewTickets,
              canViewConversations,
              canViewChats,
              showArchived,
            ),
          )}
        </title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          height: '100%',
          display: 'flex',
          overflow: 'hidden',
        }}
      >
        <>
          <Box
            sx={{
              display: 'flex',
              flex: 1,
              width: '100%',
              minWidth: 0,
            }}
          >
            <ChatsSidebar
              hide={hideSidebar}
              start={
                isResponsible && (
                  <NewTickets
                    count={amountOfTicketsWhichNeedAttention}
                    sx={{ mr: 1 }}
                  />
                )
              }
              title={getChatModuleName(
                canViewTickets,
                canViewChats,
                showArchived,
              )}
              actions={<NewMenu />}
              onlyTitle={showArchived}
              onBackClick={handleGoBack}
              searchBar={
                canViewChats &&
                !showArchived && (
                  <SearchBar
                    query={query}
                    onChange={handleChange}
                    placeholder={t('SEARCH_CHATS')}
                    withoutDivider
                    isChat
                  />
                )
              }
            >
              {query && emptyInbox && (
                <>
                  <Typography
                    color="primary"
                    sx={{ ml: 4, mt: 1 }}
                  >
                    {t('CHATS')}
                  </Typography>
                </>
              )}
              {!showArchived && dataArchivedCount > 0 && (
                <ArchiveChatButton
                  onClick={setShowArchived}
                  archivedCount={dataArchivedCount}
                />
              )}
              <ThreadList
                showArchivedChats={showArchived}
                {...chatsToShow}
                isChat
              />
            </ChatsSidebar>
            {showChat && <Outlet />}
          </Box>
        </>
      </Box>
    </>
  );
};

export default Chats;
