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

import { useNavigate } from 'react-router-dom';

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

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 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 ChatsSidebar from 'src/components/dashboard/chat/ChatsSidebar';
import { useTranslation } from 'src/components/dashboard/chat/i18n';
import { chatRoutes } from 'src/components/dashboard/chat/routes';
import PeopleSearch from 'src/components/dashboard/people/PeopleSearch';
import { peopleSearchKeys } from 'src/components/dashboard/people/queries';

const LIMIT = 100;

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

  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(t('NEW_CHAT'))}</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={t('NEW_CHAT')}
            onlyTitle
            onBackClick={handleCancel}
          >
            <PeopleSearch
              queryKey={peopleSearchKeys.searchChatUsers}
              onSelect={handleSelect}
              limit={LIMIT}
              filterSelf
            />
          </ChatsSidebar>
          {!isMobile && <ChatEmpty />}
        </Box>
      </Box>
    </>
  );
};

export default ChatNewOneToOne;
