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

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

import randomColor from 'randomcolor';

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 { uploadImage } from 'src/services/attachments';
import { createGroupChat } from 'src/services/chats';
import { EventName } from 'src/types/amplitude';
import { User } from 'src/types/user';
import { formatTitle } from 'src/utils/helmetUtils';

import {
  SelectParticipants,
  InputInfo,
} from 'src/components/dashboard/chat/ChatNewGroup';
import ChatSidebarStepper from 'src/components/dashboard/chat/ChatSidebarStepper';
import { useTranslation } from 'src/components/dashboard/chat/i18n';
import { chatRoutes } from 'src/components/dashboard/chat/routes';

const MIN_PARTICIPANTS = 1;

const ChatNewGroup: FC = () => {
  const [participants, setParticipants] = useState<User[]>([]);
  const [image, setImage] = useState(null);
  const [title, setTitle] = useState<string>('');
  // eslint-disable-next-line react/hook-use-state
  const [color] = useState(randomColor());

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

  const { t } = useTranslation();
  const showGeneralError = useGeneralError();
  const navigate = useNavigate();

  const { isLoading, mutate: handleCreate } = useMutation(
    async () => {
      const { url: pictureUrl } = image
        ? await uploadImage(image)
        : { url: null };

      const body = {
        title,
        pictureUrl,
        userIds: participants.map(user => user.id),
        color,
      };

      return createGroupChat(body);
    },
    {
      onSuccess: response => {
        const { data: thread } = response;
        const chatId = thread.chat.id;
        const state = thread;

        logEvent(EventName.CHAT_GROUP_CREATE, { chatId });

        navigate(chatRoutes.thread.detail(chatId), { state });
      },
      onError: err => {
        showGeneralError(err, t('ERROR_CREATING_CHAT'));
      },
    },
  );

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

  const handleFinish = () => {
    handleCreate();
  };

  const handleAddParticipant = (user: User) => {
    setParticipants([...participants, user]);
  };

  const handleDeleteParticipant = (index: number) => {
    const newParticipants = [...participants];
    newParticipants.splice(index, 1);
    setParticipants(newParticipants);
  };

  const handleChangeImage = newImage => {
    setImage(newImage);
  };

  const handleChangeTitle = newTitle => {
    setTitle(newTitle);
  };

  const isValidInfo = () => !!title && title.trim().length > 0;

  const isValidParticipants = () => participants?.length >= MIN_PARTICIPANTS;

  const steps = [
    {
      id: 'participants',
      title: t('ADD_PARTICIPANTS'),
      children: (
        <SelectParticipants
          selected={participants}
          onAdd={handleAddParticipant}
          onDelete={handleDeleteParticipant}
        />
      ),
      buttonProps: {
        disabled: !isValidParticipants(),
      },
    },
    {
      id: 'info',
      title: t('NEW_GROUP'),
      children: (
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center',
            pt: 2,
          }}
        >
          <InputInfo
            color={color}
            onChangeImage={handleChangeImage}
            onChangeTitle={handleChangeTitle}
            imageFieldProps={{ label: t('GROUP_IMAGE') }}
            textFieldProps={{
              sx: { my: 2, height: 'auto' },
              label: t('GROUP_TITLE'),
            }}
          />
        </Box>
      ),
      buttonLabel: isLoading ? t('LOADING_CREATE') : t('CREATE'),
      buttonProps: {
        disabled: !isValidInfo() || isLoading,
        loading: isLoading,
      },
    },
  ];

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('NEW_GROUP'))}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          height: '100%',
          display: 'flex',
        }}
      >
        <Box
          sx={{
            flex: 1,
            width: '100%',
            overflow: isMobile ? 'hidden' : 'auto',
          }}
        >
          <ChatSidebarStepper
            steps={steps}
            onCancel={handleCancel}
            onFinish={handleFinish}
          />
          {!isMobile && <ChatEmpty />}
        </Box>
      </Box>
    </>
  );
};

export default ChatNewGroup;
