import { FC, useState } from 'react';
import { useForm } from 'react-hook-form';
import { useMutation } from 'react-query';

import CancelOutlinedIcon from '@material-hu/icons/material/CancelOutlined';
import CheckCircleOutlineIcon from '@material-hu/icons/material/CheckCircleOutline';
import CloseIcon from '@material-hu/icons/material/Close';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import IconButton from '@material-hu/mui/IconButton';

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

import useGeneralError from 'src/hooks/useGeneralError';
import { useMassiveAssign } from 'src/pages/dashboard/forms/MassiveAssignContext';
import { bulkAssign, bulkReview } from 'src/services/forms';
import { FormStatus, AssignBulkBody, ReviewBulkBody } from 'src/types/forms';
import { createBulkBody } from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormConfirmationDialogWithReason from './FormConfirmationDialogWithReason';

export type BulkActionsProps = {
  isBulkAssign?: boolean;
};

export const BulkActions: FC<BulkActionsProps> = props => {
  const { isBulkAssign = false } = props;

  const [isOpen, setIsOpen] = useState(false);
  const [isApprove, setIsApprove] = useState(false);

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

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

  const { reset } = form;

  const { selectedItems, canExecuteBulkAction, resetSelection } =
    useMassiveAssign();

  const { mutate: assignMutation, isLoading: assignLoading } = useMutation(
    (data: AssignBulkBody) => bulkAssign(data),
    {
      onSuccess: () => {
        resetSelection();
        enqueueSnackbar({
          title: t('BULK_ASSIGN_SUCCESS'),
          variant: 'success',
        });
      },
      onError: err => {
        showGeneralError(err, t('ERROR_ASSIGNING_FORM'));
      },
    },
  );

  const { mutate: reviewMutation, isLoading: reviewLoading } = useMutation(
    (data: ReviewBulkBody) => bulkReview(data),
    {
      onSuccess: () => {
        resetSelection();
        enqueueSnackbar({
          title: t('BULK_REVIEW_SUCCESS'),
          variant: 'success',
        });
      },
      onError: err => {
        showGeneralError(err, t('ERROR_CLOSING_FORM'));
      },
    },
  );

  const isLoading = assignLoading || reviewLoading;

  const amountOfItems = selectedItems.length;

  const handleConfirm = () => {
    if (isBulkAssign) {
      const body = createBulkBody(selectedItems);

      assignMutation(body);
    } else {
      setIsOpen(true);
      setIsApprove(true);
    }
  };

  const handleReject = () => {
    setIsOpen(true);
    setIsApprove(false);
  };

  const resetModal = () => {
    setIsApprove(false);
    setIsOpen(false);
    reset();
  };

  const submit = ({ message }) => {
    const approvalWorkflows = selectedItems.map(({ stepId, formId }) => ({
      stepId,
      formId,
    }));
    const decision = isApprove ? FormStatus.APPROVED : FormStatus.REJECTED;
    reviewMutation({ approvalWorkflows, decision, message });
    resetModal();
  };

  return (
    <>
      <Box
        sx={theme => ({
          mt: 1,
          display: 'flex',
          justifyContent: 'space-between',
          backgroundColor: theme.palette.new.background.elements.grey,
          padding: '5px 10px',
        })}
      >
        {isLoading && <CircularProgress />}
        {!isLoading && (
          <>
            <Button
              disabled={!canExecuteBulkAction}
              color="success"
              onClick={handleConfirm}
              startIcon={<CheckCircleOutlineIcon />}
            >
              {isBulkAssign ? t('ASSIGN') : t('APPROVE_FORM')}
            </Button>
            {!isBulkAssign && (
              <Button
                disabled={!canExecuteBulkAction}
                color="error"
                onClick={handleReject}
                startIcon={<CancelOutlinedIcon />}
              >
                {t('REJECT_FORM')}
              </Button>
            )}
            <IconButton onClick={resetSelection}>
              <CloseIcon />
            </IconButton>
          </>
        )}
      </Box>
      <FormConfirmationDialogWithReason
        open={isOpen}
        title={t(isApprove ? 'BULK_APPROVE' : 'BULK_REJECT')}
        acceptLabel={isApprove ? t('APPROVE_FORM') : t('REJECT_FORM')}
        description={t('BULK_COMMENT_ADD', { count: amountOfItems })}
        placeholder={t('post:add_comment')}
        submit={submit}
        showCancel
      />
    </>
  );
};

export default BulkActions;
