import { type FC } 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 Typography from '@material-hu/mui/Typography';

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

import useGeneralError from 'src/hooks/useGeneralError';
import { editMessage } from 'src/services/chats';
import { extractTextFromHTML } from 'src/utils/feed';

import CommentRichTextInput from 'src/components/comments/CommentRichTextInput';
import { useTranslation } from 'src/components/dashboard/chat/i18n';

export type ChatEditMessageProps = {
  body: string;
  closeInputToEditMessage: () => void;
  messageId: string | number;
  chatId: number;
};

const editMessageWrap = ({
  chatId,
  messageId,
  body,
}: {
  chatId: number;
  messageId: string | number;
  body: { text: string };
}) => editMessage(chatId, messageId, body);

export const ChatEditMessage: FC<ChatEditMessageProps> = props => {
  const { body, closeInputToEditMessage, messageId, chatId } = props;
  const { t } = useTranslation();
  const showGeneralError = useGeneralError();

  const postMutation = useMutation(editMessageWrap, {
    onSuccess: () => closeInputToEditMessage(),
    onError: err => {
      showGeneralError(err, t('EDIT_MESSAGE_ERROR'));
      closeInputToEditMessage();
    },
  });

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

  const { handleSubmit } = form;

  const submit = (values: { bodyHtml: string }) => {
    const { plainText } = extractTextFromHTML(values.bodyHtml);
    postMutation.mutate({ chatId, messageId, body: { text: plainText } });
  };

  return (
    <Box>
      <FormProvider {...form}>
        <form
          noValidate
          onSubmit={handleSubmit(submit)}
        >
          <CommentRichTextInput
            name="bodyHtml"
            placeholder={t('WRITE_MESSAGE')}
            initialContent={body}
            onEnterSubmit={closeInputToEditMessage}
            onEscapeKey={closeInputToEditMessage}
            autoFocus
            sx={{
              '& .tiptap': { maxHeight: '300px' },
            }}
          />
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'flex-start',
            }}
          >
            <Typography
              noWrap
              variant="subtitle2"
              component="span"
              sx={{
                display: 'inline',
                '& .MuiButton-label': {
                  textTransform: 'lowercase',
                },
              }}
            >
              {t('ESCAPE_TO')}
              <Button
                onClick={closeInputToEditMessage}
                disabled={postMutation.isLoading}
              >
                {t('CANCEL')}
              </Button>
              {t('ENTER_TO')}
              <Button
                onClick={handleSubmit(submit)}
                disabled={postMutation.isLoading}
              >
                {t('SAVE')}
              </Button>
            </Typography>

            {postMutation.isLoading && (
              <Box sx={{ textAlign: 'center' }}>
                <CircularProgress
                  color="secondary"
                  sx={{
                    height: '16px',
                    width: '16px',
                  }}
                />
              </Box>
            )}
          </Box>
        </form>
      </FormProvider>
    </Box>
  );
};

export default ChatEditMessage;
