import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["container", "title", "description", "children", "onConfirm", "confirmComponent", "customMessages", "onCloseDialog"];
import { Box, Button, Checkbox, CircularProgress, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, FormControlLabel, Typography, useMediaQuery } from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import produce from 'immer';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { FormattedMessage, useIntl, defineMessage } from 'react-intl';
import { hasCaptcha, hasConsent, hasPreview, hasPrint } from './customizations';
import { PrintButton } from './PrintButton';
import Field from './Review/Field';
import { Customize } from './utils';
import { useGoogleReCaptcha } from 'react-google-recaptcha-v3';
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var sendErrorMessages = {
  10: defineMessage({
    id: "AqWjHF",
    defaultMessage: [{
      "type": 0,
      "value": "Lomakkeen lähetys ei onnistunut."
    }]
  }),
  40: defineMessage({
    id: "ylKM8r",
    defaultMessage: [{
      "type": 0,
      "value": "Lomakkeen lähetys ei onnistunut, koska liitetiedostojen virustarkistus epäonnistui."
    }]
  }),
  50: defineMessage({
    id: "2T0Ypn",
    defaultMessage: [{
      "type": 0,
      "value": "Lomakkeen lähetys ei onnistunut, koska captchatarkistus epäonnistui."
    }]
  })
};
export default /*#__PURE__*/forwardRef(function ConfirmDialog(_ref, ref) {
  var _otherProps$config, _customMessages$confi, _customMessages$confi2, _customMessages$confi3, _customMessages$confi4;

  var container = _ref.container,
      title = _ref.title,
      description = _ref.description,
      children = _ref.children,
      onConfirm = _ref.onConfirm,
      confirmComponent = _ref.confirmComponent,
      customMessages = _ref.customMessages,
      onCloseDialog = _ref.onCloseDialog,
      otherProps = _objectWithoutProperties(_ref, _excluded);

  useImperativeHandle(ref, function () {
    return {
      confirm: function confirm() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }

        return new Promise(function (resolve) {
          confirmRef.current = function (confirm) {
            resolve(hasCaptcha(otherProps) ? confirm && produce(args, function (_ref2) {
              var _ref3 = _slicedToArray(_ref2, 1),
                  data = _ref3[0];

              data.captchaChallenge = confirm;
            }) : confirm);
          };

          setOpen(true);
        });
      },
      loading: function loading() {
        handleLoading();
      },
      close: function close() {
        handleClose();
      },
      error: function error(data) {
        handleError(data);
      }
    };
  }); // const dialogContentFlexNoneClasses = useStylesDialogContentFlexNone();

  var pageTitlesArray = otherProps === null || otherProps === void 0 ? void 0 : (_otherProps$config = otherProps.config) === null || _otherProps$config === void 0 ? void 0 : _otherProps$config.elements.filter(function (x) {
    return x.type === 'pageTitle' && x.content;
  });
  var confirmRef = useRef();
  var hasCaptchaValue = hasCaptcha(otherProps);
  var hasConsentValue = hasConsent(otherProps);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      open = _useState2[0],
      setOpen = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      loading = _useState4[0],
      setLoading = _useState4[1];

  var _useState5 = useState(null),
      _useState6 = _slicedToArray(_useState5, 2),
      error = _useState6[0],
      setError = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      consent = _useState8[0],
      setConsent = _useState8[1];

  var intl = useIntl();

  var _useGoogleReCaptcha = useGoogleReCaptcha(),
      executeRecaptcha = _useGoogleReCaptcha.executeRecaptcha;

  function handleClose() {
    setLoading(false);
    setError(false);
    setOpen(false);
    onCloseDialog === null || onCloseDialog === void 0 ? void 0 : onCloseDialog();
  }

  function handleDismiss() {
    if (!loading || error) {
      setLoading(false);
      setError(null);
      handleClose();
      confirmRef.current(false);
    }
  }

  function handleLoading() {
    setLoading(true);
  }

  function handleError(data) {
    setError(sendErrorMessages[data.errorCode] ? intl.formatMessage(sendErrorMessages[data.errorCode]) : data.message);
    setLoading(false);
  }

  function handleConfirm() {
    return _handleConfirm.apply(this, arguments);
  }

  function _handleConfirm() {
    _handleConfirm = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var token;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!hasCaptchaValue) {
                _context.next = 7;
                break;
              }

              _context.next = 3;
              return executeRecaptcha('submit');

            case 3:
              token = _context.sent;
              confirmRef.current(token);
              _context.next = 8;
              break;

            case 7:
              confirmRef.current(true);

            case 8:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
    return _handleConfirm.apply(this, arguments);
  }

  return /*#__PURE__*/_jsx(Customize, _objectSpread(_objectSpread({
    customizer: confirmComponent
  }, otherProps), {}, {
    children: /*#__PURE__*/_jsxs(Dialog, {
      scroll: "body",
      open: open,
      onClose: handleDismiss,
      "aria-labelledby": "confirm-dialog-title",
      "aria-describedby": "confirm-dialog-description",
      fullScreen: useMediaQuery('print'),
      container: container,
      disableBackdropClick: true,
      children: [/*#__PURE__*/_jsx(DialogTitle, {
        id: "confirm-dialog-title",
        children: title
      }), /*#__PURE__*/_jsxs(DialogContent, {
        children: [description && /*#__PURE__*/_jsx(DialogContentText, {
          id: "confirm-dialog-description",
          children: description
        }), hasPreview(otherProps) && /*#__PURE__*/_jsxs(_Fragment, {
          children: [/*#__PURE__*/_jsx(Typography, {
            variant: "subtitle1",
            component: "h3",
            children: (_customMessages$confi = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogPreview) !== null && _customMessages$confi !== void 0 ? _customMessages$confi : /*#__PURE__*/_jsx(FormattedMessage, {
              id: "gkQhRC",
              defaultMessage: [{
                "type": 0,
                "value": "Lähetettävien tietojen esikatselu"
              }]
            })
          }), /*#__PURE__*/_jsx(Field, _objectSpread({
            preview: true // For selecting optional preview / review customization
            ,
            root: true,
            pageTitles: pageTitlesArray
          }, otherProps))]
        }), hasConsentValue && /*#__PURE__*/_jsx(FormControlLabel, {
          control: /*#__PURE__*/_jsx(Checkbox, {
            checked: consent,
            onChange: function onChange(event) {
              setConsent(event.target.checked);
            },
            name: "consent",
            color: "secondary"
          }),
          label: (_customMessages$confi2 = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogConsent) !== null && _customMessages$confi2 !== void 0 ? _customMessages$confi2 : intl.formatMessage({
            id: "BFjxIc",
            defaultMessage: [{
              "type": 0,
              "value": "Vahvistan ilmoitetut tiedot oikeiksi"
            }]
          })
        }, "consent"), loading && /*#__PURE__*/_jsx("div", {
          children: /*#__PURE__*/_jsx(CircularProgress, {})
        }), error && /*#__PURE__*/_jsx(DialogContentText, {
          children: /*#__PURE__*/_jsx(Alert, {
            severity: "error",
            children: error
          })
        })]
      }), /*#__PURE__*/_jsx(Box, {
        displayPrint: "none",
        children: /*#__PURE__*/_jsxs(DialogActions, {
          children: [/*#__PURE__*/_jsx(Button, {
            disabled: loading && !error,
            onClick: handleDismiss,
            children: (_customMessages$confi3 = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogCancelButton) !== null && _customMessages$confi3 !== void 0 ? _customMessages$confi3 : /*#__PURE__*/_jsx(FormattedMessage, {
              id: "/FfZeC",
              defaultMessage: [{
                "type": 0,
                "value": "Peruuta"
              }]
            })
          }), hasPreview(otherProps) && hasPrint(otherProps) && /*#__PURE__*/_jsx(PrintButton, {}), /*#__PURE__*/_jsx(Button, {
            disabled: hasConsentValue && !consent || loading || error || !loading && hasCaptchaValue && !executeRecaptcha,
            onClick: handleConfirm,
            variant: "contained",
            color: "primary",
            autoFocus: true,
            children: (_customMessages$confi4 = customMessages === null || customMessages === void 0 ? void 0 : customMessages.confirmDialogSendButton) !== null && _customMessages$confi4 !== void 0 ? _customMessages$confi4 : /*#__PURE__*/_jsx(FormattedMessage, {
              id: "6jFMKd",
              defaultMessage: [{
                "type": 0,
                "value": "Lähetä"
              }]
            })
          })]
        })
      })]
    })
  }));
});
//# sourceMappingURL=ConfirmDialog.js.map