import { FC } from 'react';
import { Helmet } from 'react-helmet-async';
import { useNavigate } from 'react-router-dom';

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

import { logEvent } from 'src/config/logging';
import useGeneralError from 'src/hooks/useGeneralError';
import usePermissions from 'src/hooks/usePermissions';
import ChatEmpty from 'src/pages/dashboard/chats/ChatEmpty';
import { createChat } from 'src/services/chats';
import { EventName } from 'src/types/amplitude';
import { User } from 'src/types/user';
import { formatTitle } from 'src/utils/helmetUtils';
import { UserPermissions } from 'src/utils/permissions';

import ChatsSidebar from 'src/components/dashboard/chat/ChatsSidebar';
import { useTranslation } from 'src/components/dashboard/chat/i18n';
import PeopleAndTicketSearch from 'src/components/dashboard/chat/PeopleAndTicketSearch';
import { chatRoutes } from 'src/components/dashboard/chat/routes';

const { VIEW_REGULAR_CHATS } = UserPermissions;

const LIMIT = 100;

const ChatNewGeneric: FC = () => {
  const { t } = useTranslation();
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();

  const { hasAll: canViewChats } = usePermissions([VIEW_REGULAR_CHATS]);

  const title = canViewChats ? t('NEW_CHAT') : t('NEW_TICKET');

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

  const handleSelect = async (user: User) => {
    try {
      const { data: thread } = await createChat(user.id);

      const chatId = thread.chat.id;
      const userId = thread.chat?.otherUser.id;
      const state = thread;

      logEvent(EventName.CHAT_SINGLE_CREATE, { chatId, userId });

      navigate(chatRoutes.thread.detail(chatId), { state });
    } catch (err) {
      showGeneralError(err, t('ERROR_CREATING_CHAT'));
    }
  };

  const handleCancel = () => navigate(chatRoutes.chats());

  return (
    <>
      <Helmet>
        <title>{formatTitle(title)}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          height: '100%',
          display: 'flex',
        }}
      >
        <Box
          sx={{
            display: 'flex',
            flex: 1,
            width: '100%',
            overflow: isMobile ? 'hidden' : 'auto',
          }}
        >
          <ChatsSidebar
            title={title}
            onlyTitle
            onBackClick={handleCancel}
          >
            <PeopleAndTicketSearch
              onUserSelect={handleSelect}
              limit={LIMIT}
            />
          </ChatsSidebar>
          {!isMobile && <ChatEmpty />}
        </Box>
      </Box>
    </>
  );
};

export default ChatNewGeneric;
