import { FC, useState, memo } from 'react';
import { useForm, FormProvider } from 'react-hook-form';

import { useMutation } from 'react-query';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Dialog from '@material-hu/mui/Dialog';
import DialogActions from '@material-hu/mui/DialogActions';
import DialogContent from '@material-hu/mui/DialogContent';
import DialogTitle from '@material-hu/mui/DialogTitle';

import Button from '@material-hu/components/design-system/Buttons/Button';

import useGeneralError from 'src/hooks/useGeneralError';
import SearchIcon from 'src/icons/Search';
import { forwardMessage } from 'src/services/chats';
import { useTranslation } from 'src/components/dashboard/chat/i18n';

import { FormTextField } from 'src/components/FormInputs';

import SearchPeopleOrGroup from './SearchPeopleOrGroup';

export type ChatForwardMessageProps = {
  open: boolean;
  onCancel: (event) => void;
  messageId: string | number;
  chatId: number;
};

const forwardMessageWrap = ({ chatId, messageId, body }) =>
  forwardMessage(chatId, messageId, body);

export const ChatForwardMessage: FC<ChatForwardMessageProps> = props => {
  const { open, onCancel, messageId, chatId } = props;

  const [users, setUsers] = useState([]);
  const [groups, setGroups] = useState([]);

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

  const postMutation = useMutation(forwardMessageWrap);

  const form = useForm({
    defaultValues: {
      query: '',
    },
  });

  const { watch } = form;

  const handleCancel = event => {
    onCancel(event);
  };

  const handleAccept = async event => {
    try {
      if (users.length > 0 || groups.length > 0) {
        await postMutation.mutateAsync({
          chatId,
          messageId,
          body: { users, groups },
        });
      }
      onCancel(event);
    } catch (error) {
      showGeneralError(error, t('FORWARD_MESSAGE_ERROR'));
      onCancel(event);
    }
  };

  const query = watch('query');

  return (
    <Dialog
      open={open}
      maxWidth="sm"
      fullWidth
    >
      <DialogTitle>{t('FORWARD_MESSAGE')}</DialogTitle>
      <DialogContent dividers>
        <Box
          sx={{
            alignItems: 'center',
            backgroundColor: 'background.default',
            borderRadius: 22,
            display: 'flex',
            height: 44,
            px: 2,
            mx: 1,
          }}
        >
          <SearchIcon
            color="action"
            fontSize="small"
          />
          <Box
            sx={{
              flexGrow: 1,
              m: 2,
            }}
          >
            <FormProvider {...form}>
              <form noValidate>
                <FormTextField
                  name="query"
                  ariaLabel={t('SEARCH_PEOPLE_GROUP')}
                  placeholder={t('SEARCH_PEOPLE_GROUP')}
                  fullWidth
                  sx={{
                    '& fieldset': {
                      borderColor: 'transparent !important',
                    },
                  }}
                />
              </form>
            </FormProvider>
          </Box>
        </Box>
        <SearchPeopleOrGroup
          query={query}
          users={users}
          setUsers={setUsers}
          groups={groups}
          setGroups={setGroups}
        />
      </DialogContent>
      <DialogActions>
        <Button
          disabled={postMutation.isLoading}
          color="secondary"
          onClick={handleCancel}
          sx={{ mr: 1 }}
        >
          {t('CANCEL')}
        </Button>
        <Button
          disabled={postMutation.isLoading}
          onClick={handleAccept}
        >
          {t('RESEND')}
        </Button>
        {postMutation.isLoading && (
          <Box sx={{ textAlign: 'center' }}>
            <CircularProgress />
          </Box>
        )}
      </DialogActions>
    </Dialog>
  );
};

export default memo(ChatForwardMessage);
