import { FC } from 'react';
import { useForm, FormProvider } from 'react-hook-form';
import { useMutation, useQueryClient } 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 useSnackbar from '@material-hu/components/design-system/Snackbar';

import { logEvent } from 'src/config/logging';
import useGeneralError from 'src/hooks/useGeneralError';
import { useMassiveAssign } from 'src/pages/dashboard/forms/MassiveAssignContext';
import { closeApprovalWorkflow } from 'src/services/forms';
import { EventName } from 'src/types/amplitude';
import { StepType } from 'src/types/forms';
import { getStatusFormForAmplitude } from 'src/utils/amplitude';
import {
  getStatusFormForRequest,
  handleErrorToAddComment,
} from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  updateListsForms,
  formKeys,
} from 'src/components/dashboard/form/queries';
import FormTextField from 'src/components/FormInputs/FormTextField';

export type DialogAddCommentProps = {
  id: number;
  templateId: number;
  steps: StepType[];
  open: boolean;
  title: string;
  approveForm?: boolean;
  rejectForm?: boolean;
  handleCancel: () => void;
};

const closeApprovalWorkflowWrap = ({ formId, stepId, body }) =>
  closeApprovalWorkflow(formId, stepId, body);

const DialogAddComment: FC<DialogAddCommentProps> = props => {
  const {
    id,
    templateId,
    steps,
    open,
    title,
    handleCancel,
    approveForm = false,
    rejectForm = false,
  } = props;

  const { t } = useLokaliseTranslation('forms');
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();
  const queryClient = useQueryClient();

  const { removeItem } = useMassiveAssign();

  // TODO: analizar de usar onMutate en la etapa de mejoras en la app, para evitar hacer updateListsForms();
  const { mutate, isLoading } = useMutation(closeApprovalWorkflowWrap, {
    onSuccess: response => {
      logEvent(EventName.FORM_APPROVAL_CLOSE, {
        formFilledId: templateId,
        formId: id,
        status: getStatusFormForAmplitude(approveForm, rejectForm),
        hasMessage: !!response.data.message,
      });

      queryClient.invalidateQueries(formKeys.formApprovalWorkflow(Number(id)));
      removeItem(Number(id));
      updateListsForms();
      enqueueSnackbar({ title: t('SUCCESS_ADD_COMMENT'), variant: 'success' });
      handleCancel();
    },
    onError: err => showGeneralError(err, handleErrorToAddComment(err)),
    onSettled: () => {
      reset();
      handleCancel();
    },
  });

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

  const {
    handleSubmit,
    reset,
    formState: { isSubmitting },
  } = form;

  const submit = ({ comment }) => {
    const lastStep = steps[steps.length - 1];
    const body = {
      decision: getStatusFormForRequest(approveForm, rejectForm),
      message: comment,
    };
    mutate({
      formId: id,
      stepId: lastStep.stepId,
      body,
    });
  };

  return (
    <Dialog
      open={open}
      maxWidth="sm"
      fullWidth
    >
      <DialogTitle>{title}</DialogTitle>
      <DialogContent dividers>
        <Box
          sx={{
            alignItems: 'center',
            display: 'flex',
            height: 'fit-content',
            px: 2,
            mx: 1,
          }}
        >
          <Box
            sx={{
              flexGrow: 1,
              m: 2,
            }}
          >
            <FormProvider {...form}>
              <form
                noValidate
                onSubmit={handleSubmit(submit)}
              >
                <FormTextField
                  multiline
                  inputProps={{ maxLength: 1024 }}
                  autoFocus
                  name="comment"
                  placeholder={t('ADD_COMMENT')}
                />
              </form>
            </FormProvider>
          </Box>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button
          disabled={isSubmitting || isLoading}
          color="secondary"
          onClick={() => {
            reset();
            handleCancel();
          }}
          sx={{ mr: 1 }}
        >
          {t('CANCEL')}
        </Button>
        <Button
          disabled={isLoading}
          onClick={handleSubmit(submit)}
        >
          {approveForm && t('FORMS:APPROVE_FORM')}
          {rejectForm && t('FORMS:REJECT_FORM')}
        </Button>
        {isLoading && (
          <Box sx={{ textAlign: 'center' }}>
            <CircularProgress />
          </Box>
        )}
      </DialogActions>
    </Dialog>
  );
};

export default DialogAddComment;
