'use strict';

var LeftArrow = require('@bigbinary/neeto-icons/LeftArrow');
var Button = require('@bigbinary/neetoui/Button');
var Typography = require('@bigbinary/neetoui/Typography');
var Form$1 = require('@bigbinary/neetoui/formik/Form');
var reactI18next = require('react-i18next');
var EmailPreview = require('./EmailPreview.js');
var MobilePreviewHeader = require('./MobilePreviewHeader.js');
var React = require('react');
var formik = require('formik');
var Input = require('@bigbinary/neetoui/formik/Input');
var ActionBlock = require('@bigbinary/neetoui/formik/ActionBlock');
var SendToFields = require('./SendToFields.js');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var classnames = require('classnames');
var Down = require('@bigbinary/neeto-icons/Down');
var Up = require('@bigbinary/neeto-icons/Up');
var Label = require('@bigbinary/neetoui/Label');
var Switch = require('@bigbinary/neetoui/formik/Switch');
var ramda = require('ramda');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var DatePicker = require('@bigbinary/neetoui/DatePicker');
var i18next = require('i18next');
var neetoCist = require('@bigbinary/neeto-cist');
var utils$1 = require('@bigbinary/neeto-commons-frontend/utils');
var utils = require('@bigbinary/neeto-editor/utils');
var yup = require('yup');
var jsxRuntime = require('react/jsx-runtime');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var FormikEditor = require('@bigbinary/neeto-editor/FormikEditor');
var injectCss = require('./inject-css-B6qYtOJe.js');
require('@bigbinary/neeto-commons-frontend/react-utils/withT');
require('@bigbinary/neeto-editor/EditorContent');
require('./index-JY2zVpnv.js');
require('./_commonjsHelpers-BJu3ubxk.js');
require('@bigbinary/neeto-icons/Upload');
require('@bigbinary/neetoui/Toastr');
require('@bigbinary/neetoui/formik/MultiEmailInput');
require('@bigbinary/neetoui/Pane');
require('react-dropzone');
require('@bigbinary/neeto-icons/Download');
require('@bigbinary/neetoui/Callout');
require('stream');

function _interopNamespaceDefault(e) {
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var yup__namespace = /*#__PURE__*/_interopNamespaceDefault(yup);

var INITIAL_VALUES = {
  sendFromEmail: "",
  replyToEmail: "",
  notifyEmails: [],
  emailSubject: "",
  emailBody: "",
  isSendLaterEnabled: false,
  sendEmailDatetime: undefined,
  category: "email_share",
  actionButtonText: ""
};
var EDITOR_ADDONS = ["emoji", "block-quote", "image-upload", "divider"];
var TIME_FORMAT = "hh:mm A";

function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var isPastDate = function isPastDate(date) {
  return utils$1.dayjs(date).isBefore(utils$1.dayjs().subtract(1, "days"));
};
var generateInitialValues = function generateInitialValues(defaultValues) {
  return _objectSpread$1(_objectSpread$1({}, INITIAL_VALUES), defaultValues);
};
var emailFormValidationSchema = function emailFormValidationSchema(disableReplyTo) {
  return yup__namespace.object().shape({
    emailSubject: yup__namespace.string().required(i18next.t("neetoMolecules.shareViaEmail.validations.requiredField.subject")),
    emailBody: yup__namespace.string().test("emailBody", i18next.t("neetoMolecules.shareViaEmail.validations.requiredField.emailBody"), function (value) {
      return !utils.isEditorEmpty(value);
    }),
    sendFromEmail: yup__namespace.string().trim().email(i18next.t("neetoMolecules.shareViaEmail.validations.invalidField.emailAddress")).required(i18next.t("neetoMolecules.shareViaEmail.validations.requiredField.sendFrom")),
    replyToEmail: !disableReplyTo && yup__namespace.string().trim().email(i18next.t("neetoMolecules.shareViaEmail.validations.invalidField.emailAddress")).required(i18next.t("neetoMolecules.shareViaEmail.validations.requiredField.replyTo")),
    notifyEmails: yup__namespace.array().min(1, i18next.t("neetoMolecules.shareViaEmail.validations.atleastOneIsRequired.emailAddress")).test("are-all-emails-valid", i18next.t("neetoMolecules.shareViaEmail.validations.invalidField.emailAddress"), function (emails) {
      return emails.every(ramda.prop("valid"));
    }),
    isSendLaterEnabled: yup__namespace["boolean"](),
    sendEmailDatetime: yup__namespace.date().when("isSendLaterEnabled", {
      is: true,
      then: yup__namespace.date().required(i18next.t("neetoMolecules.shareViaEmail.validations.requiredField.sendLater"))
    }),
    name: yup__namespace.string(),
    actionButtonText: yup__namespace.string().required(i18next.t("neetoMolecules.shareViaEmail.validations.requiredField.startButtonText"))
  });
};
var disabledTime = function disabledTime(selectedDate) {
  var current = utils$1.dayjs(selectedDate).startOf("day");
  var today = utils$1.dayjs().startOf("day");
  if (current.isBefore(today)) {
    return {
      disabledHours: function disabledHours() {
        return neetoCist.dynamicArray(24, function (i) {
          return i;
        });
      },
      disabledMinutes: function disabledMinutes() {
        return neetoCist.dynamicArray(60, function (i) {
          return i;
        });
      }
    };
  }
  if (current.isSame(today)) {
    var currentTime = utils$1.dayjs();
    var currentHour = currentTime.hour();
    var currentMinute = currentTime.minute();
    return {
      disabledHours: function disabledHours() {
        return neetoCist.dynamicArray(currentHour, function (i) {
          return i;
        });
      },
      disabledMinutes: function disabledMinutes(selectedHour) {
        return selectedHour === currentHour ? neetoCist.dynamicArray(currentMinute, function (i) {
          return i;
        }) : [];
      }
    };
  }
  return {};
};

var _excluded = ["name", "disabledDate"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var FormikDatePicker = function FormikDatePicker(_ref) {
  var name = _ref.name,
    disabledDate = _ref.disabledDate,
    props = _objectWithoutProperties(_ref, _excluded);
  var _useField = formik.useField(name),
    _useField2 = _slicedToArray(_useField, 3),
    field = _useField2[0],
    meta = _useField2[1],
    _useField2$ = _useField2[2],
    setValue = _useField2$.setValue,
    setTouched = _useField2$.setTouched;
  return /*#__PURE__*/jsxRuntime.jsx(DatePicker, _objectSpread(_objectSpread({
    showTime: true,
    timeFormat: TIME_FORMAT
  }, _objectSpread(_objectSpread(_objectSpread({}, field), meta), {}, {
    disabledDate: disabledDate
  })), {}, {
    "data-testid": props["data-testid"],
    timePickerProps: {
      disabledTime: disabledTime
    },
    onBlur: function onBlur() {
      return !meta.touched && setTouched(true);
    },
    onChange: function onChange(date) {
      setValue(date || undefined);
      if (!meta.touched) setTouched(true);
    }
  }, props));
};

var AdvancedProperties = function AdvancedProperties(_ref) {
  var showSendFromField = _ref.showSendFromField,
    disableReplyTo = _ref.disableReplyTo;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = formik.useFormikContext(),
    values = _useFormikContext.values;
  var _useState = React.useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isAdvancedPropertiesVisible = _useState2[0],
    setIsAdvancedPropertiesVisible = _useState2[1];
  var toggleAdvancedOptions = function toggleAdvancedOptions() {
    return setIsAdvancedPropertiesVisible(ramda.not);
  };
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "flex w-full flex-col items-start gap-4",
    children: [/*#__PURE__*/jsxRuntime.jsxs("button", {
      className: "flex w-full cursor-pointer items-start justify-between overflow-hidden border-0 py-4",
      type: "button",
      onClick: toggleAdvancedOptions,
      children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
        className: "flex min-w-0 flex-grow",
        component: "span",
        style: "h5",
        weight: "medium",
        children: t("neetoMolecules.shareViaEmail.advancedProperties")
      }), isAdvancedPropertiesVisible ? /*#__PURE__*/jsxRuntime.jsx(Up, {
        className: "flex-shrink-0",
        size: 20
      }) : /*#__PURE__*/jsxRuntime.jsx(Down, {
        className: "flex-shrink-0",
        size: 20
      })]
    }), isAdvancedPropertiesVisible && /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
      children: [/*#__PURE__*/jsxRuntime.jsx("div", {
        children: /*#__PURE__*/jsxRuntime.jsxs(Label, {
          className: "flex items-center gap-2",
          children: [/*#__PURE__*/jsxRuntime.jsx(Switch, {
            "data-testid": "send-later-switch",
            name: "isSendLaterEnabled"
          }), /*#__PURE__*/jsxRuntime.jsx(Typography, {
            component: "span",
            "data-testid": "send-later-label",
            lineHeight: "normal",
            style: "h4",
            weight: "semibold",
            children: t("neetoMolecules.shareViaEmail.sendLater")
          })]
        })
      }), values.isSendLaterEnabled && /*#__PURE__*/jsxRuntime.jsx(FormikDatePicker, {
        autoFocus: true,
        "data-testid": "email-share-date-input",
        disabledDate: isPastDate,
        name: "sendEmailDatetime",
        size: "large"
      }), /*#__PURE__*/jsxRuntime.jsx(Input, {
        required: true,
        className: "w-full",
        label: t("neetoMolecules.shareViaEmail.startButtonText"),
        name: "actionButtonText"
      }), /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex w-full flex-col gap-4 sm:flex-row sm:gap-6",
        children: [showSendFromField && /*#__PURE__*/jsxRuntime.jsx(Input, {
          required: true,
          "data-testid": "neeto-molecules-share-via-email-send-from",
          label: t("neetoMolecules.shareViaEmail.sendFrom"),
          name: "sendFromEmail",
          className: classnames({
            "w-full flex-grow-0": !disableReplyTo
          })
        }), !disableReplyTo && /*#__PURE__*/jsxRuntime.jsx(Input, {
          required: true,
          "data-testid": "replyTo-field",
          label: t("neetoMolecules.shareViaEmail.replyTo"),
          name: "replyToEmail",
          className: classnames({
            "w-full flex-grow-0": showSendFromField
          })
        })]
      })]
    })]
  });
};

var EmailBody = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
  var id = _ref.id,
    showVideoEmbedInEditor = _ref.showVideoEmbedInEditor;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  return /*#__PURE__*/jsxRuntime.jsx(FormikEditor, {
    id: id,
    ref: ref,
    required: true,
    className: "mb-6",
    "data-testid": "email-body",
    label: t("neetoMolecules.shareViaEmail.emailBody"),
    name: "emailBody",
    addons: showVideoEmbedInEditor ? [].concat(_toConsumableArray(EDITOR_ADDONS), ["video-embed"]) : EDITOR_ADDONS
  });
});
EmailBody.displayName = "EmailBody";

var Form = function Form(_ref) {
  var showSendFromField = _ref.showSendFromField,
    disableReplyTo = _ref.disableReplyTo,
    showVideoEmbedInEditor = _ref.showVideoEmbedInEditor,
    children = _ref.children;
  var _useFormikContext = formik.useFormikContext(),
    initialValues = _useFormikContext.initialValues;
  var editorRef = React.useRef();
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var handleReset = function handleReset() {
    return editorRef.current.editor.commands.setContent(initialValues.emailBody);
  };
  return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
    children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex flex-col gap-y-6",
      children: [/*#__PURE__*/jsxRuntime.jsx(SendToFields, {
        showUploadCsvButton: true,
        emailInputProps: {
          label: t("neetoMolecules.shareViaEmail.sendTo"),
          name: "notifyEmails",
          required: true
        }
      }), /*#__PURE__*/jsxRuntime.jsx(Input, {
        required: true,
        className: "col-span-1",
        label: t("neetoMolecules.shareViaEmail.subject"),
        name: "emailSubject"
      }), /*#__PURE__*/jsxRuntime.jsx(EmailBody, {
        showVideoEmbedInEditor: showVideoEmbedInEditor,
        id: "emailBody",
        ref: editorRef
      }), /*#__PURE__*/jsxRuntime.jsx("div", {
        ref: editorRef
      }), /*#__PURE__*/jsxRuntime.jsx(AdvancedProperties, {
        disableReplyTo: disableReplyTo,
        showSendFromField: showSendFromField
      })]
    }), children && /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "neeto-ui-border-gray-300 mt-4 border-t py-4",
      children: [/*#__PURE__*/jsxRuntime.jsx("h3", {
        className: "mb-4",
        children: t("neetoMolecules.shareViaEmail.additionalOptions")
      }), children]
    }), /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "neeto-ui-bg-white sticky bottom-0 z-10 mt-6 py-6",
      children: /*#__PURE__*/jsxRuntime.jsx(ActionBlock, {
        cancelButtonProps: {
          label: t("neetoMolecules.shareViaEmail.reset"),
          type: "reset",
          onClick: handleReset
        },
        submitButtonProps: {
          label: t("neetoMolecules.shareViaEmail.sendEmail")
        }
      })
    })]
  });
};

var css = "@media only screen and (min-width:768px){.neeto-molecules-share-frame{height:calc(100vh - 4rem);height:calc(100dvh - 4rem)}.neeto-molecules-share-frame__left-wrap,.neeto-molecules-share-frame__right-wrap{height:100%;overflow-y:auto}}";
injectCss.n(css,{});

var ShareViaEmail = function ShareViaEmail(_ref) {
  var _ref$showSendFromFiel = _ref.showSendFromField,
    showSendFromField = _ref$showSendFromFiel === void 0 ? false : _ref$showSendFromFiel,
    backToUrl = _ref.backToUrl,
    handleSubmit = _ref.handleSubmit,
    _children = _ref.children,
    description = _ref.description,
    defaultValues = _ref.defaultValues,
    disableReplyTo = _ref.disableReplyTo,
    showVideoEmbedInEditor = _ref.showVideoEmbedInEditor,
    _ref$title = _ref.title,
    title = _ref$title === void 0 ? "" : _ref$title;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var shareViaEmailTitle = title || t("neetoMolecules.shareViaEmail.title");
  var sendToEmails = function sendToEmails(notifyEmails) {
    return notifyEmails.map(function (email) {
      return email === null || email === void 0 ? void 0 : email.value;
    });
  };
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: "w-full",
    children: /*#__PURE__*/jsxRuntime.jsx(Form$1, {
      scrollToErrorField: true,
      formProps: {
        noValidate: true
      },
      formikProps: {
        enableReinitialize: true,
        validateOnMount: true,
        initialValues: generateInitialValues(defaultValues),
        validationSchema: emailFormValidationSchema(disableReplyTo),
        onSubmit: handleSubmit
      },
      children: function children(_ref2) {
        var values = _ref2.values;
        return /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "neeto-molecules-share-frame grid grid-cols-1 md:grid-cols-12",
          children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
            className: "neeto-molecules-share-frame__left-wrap col-span-1 p-6 pb-0 md:col-span-6 lg:col-span-5",
            "data-testid": "share-via-email-frame-wrapper",
            children: [backToUrl && /*#__PURE__*/jsxRuntime.jsx(Button, {
              className: "mb-4",
              "data-testid": "back-to-url-button",
              icon: LeftArrow,
              iconPosition: "left",
              label: t("neetoMolecules.shareViaEmail.backToShare"),
              size: "small",
              style: "link",
              to: backToUrl
            }), /*#__PURE__*/jsxRuntime.jsxs("div", {
              className: "mb-6",
              children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
                className: "mb-0.5 break-words",
                "data-testid": "share-via-email-heading",
                lineHeight: "normal",
                style: "h2",
                weight: "semibold",
                children: shareViaEmailTitle
              }), description && /*#__PURE__*/jsxRuntime.jsx(Typography, {
                className: "neeto-ui-text-gray-700",
                "data-testid": "share-via-email-sub-heading",
                lineHeight: "normal",
                style: "body2",
                children: description
              })]
            }), /*#__PURE__*/jsxRuntime.jsx(Form, {
              disableReplyTo: disableReplyTo,
              showSendFromField: showSendFromField,
              showVideoEmbedInEditor: showVideoEmbedInEditor,
              children: _children
            })]
          }), /*#__PURE__*/jsxRuntime.jsx(MobilePreviewHeader, {
            className: "col-span-1 md:hidden"
          }), /*#__PURE__*/jsxRuntime.jsx("div", {
            className: "neeto-molecules-share-frame__right-wrap neeto-ui-bg-gray-100 col-span-1 p-6 py-10 md:col-span-6 lg:col-span-7",
            children: /*#__PURE__*/jsxRuntime.jsx(EmailPreview, {
              actionButtonText: values.actionButtonText,
              body: values.emailBody,
              subject: values.emailSubject,
              to: sendToEmails(values.notifyEmails)
            })
          })]
        });
      }
    })
  });
};

module.exports = ShareViaEmail;
//# sourceMappingURL=ShareViaEmail.js.map
