import LeftArrow from '@bigbinary/neeto-icons/LeftArrow';
import Button from '@bigbinary/neetoui/Button';
import Typography from '@bigbinary/neetoui/Typography';
import Form$1 from '@bigbinary/neetoui/formik/Form';
import { useTranslation } from 'react-i18next';
import EmailPreview from './EmailPreview.js';
import MobilePreviewHeader from './MobilePreviewHeader.js';
import { useState, forwardRef, useRef } from 'react';
import { useField, useFormikContext } from 'formik';
import Input from '@bigbinary/neetoui/formik/Input';
import ActionBlock from '@bigbinary/neetoui/formik/ActionBlock';
import SendToFields from './SendToFields.js';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import classnames from 'classnames';
import Down from '@bigbinary/neeto-icons/Down';
import Up from '@bigbinary/neeto-icons/Up';
import Label from '@bigbinary/neetoui/Label';
import Switch from '@bigbinary/neetoui/formik/Switch';
import { prop, not } from 'ramda';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import DatePicker from '@bigbinary/neetoui/DatePicker';
import { t } from 'i18next';
import { dynamicArray } from '@bigbinary/neeto-cist';
import { dayjs } from '@bigbinary/neeto-commons-frontend/utils';
import { isEditorEmpty } from '@bigbinary/neeto-editor/utils';
import * as yup from 'yup';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import FormikEditor from '@bigbinary/neeto-editor/FormikEditor';
import { n } from './inject-css-C2dztUxs.js';
import '@bigbinary/neeto-commons-frontend/react-utils/withT';
import '@bigbinary/neeto-editor/EditorContent';
import './index-DAYCJu79.js';
import './_commonjsHelpers-BFTU3MAI.js';
import '@bigbinary/neeto-icons/Upload';
import '@bigbinary/neetoui/Toastr';
import '@bigbinary/neetoui/formik/MultiEmailInput';
import '@bigbinary/neetoui/Pane';
import 'react-dropzone';
import '@bigbinary/neeto-icons/Download';
import '@bigbinary/neetoui/Callout';
import 'stream';

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 dayjs(date).isBefore(dayjs().subtract(1, "days"));
};
var generateInitialValues = function generateInitialValues(defaultValues) {
  return _objectSpread$1(_objectSpread$1({}, INITIAL_VALUES), defaultValues);
};
var emailFormValidationSchema = function emailFormValidationSchema(disableReplyTo) {
  return yup.object().shape({
    emailSubject: yup.string().required(t("neetoMolecules.shareViaEmail.validations.requiredField.subject")),
    emailBody: yup.string().test("emailBody", t("neetoMolecules.shareViaEmail.validations.requiredField.emailBody"), function (value) {
      return !isEditorEmpty(value);
    }),
    sendFromEmail: yup.string().trim().email(t("neetoMolecules.shareViaEmail.validations.invalidField.emailAddress")).required(t("neetoMolecules.shareViaEmail.validations.requiredField.sendFrom")),
    replyToEmail: !disableReplyTo && yup.string().trim().email(t("neetoMolecules.shareViaEmail.validations.invalidField.emailAddress")).required(t("neetoMolecules.shareViaEmail.validations.requiredField.replyTo")),
    notifyEmails: yup.array().min(1, t("neetoMolecules.shareViaEmail.validations.atleastOneIsRequired.emailAddress")).test("are-all-emails-valid", t("neetoMolecules.shareViaEmail.validations.invalidField.emailAddress"), function (emails) {
      return emails.every(prop("valid"));
    }),
    isSendLaterEnabled: yup["boolean"](),
    sendEmailDatetime: yup.date().when("isSendLaterEnabled", {
      is: true,
      then: yup.date().required(t("neetoMolecules.shareViaEmail.validations.requiredField.sendLater"))
    }),
    name: yup.string(),
    actionButtonText: yup.string().required(t("neetoMolecules.shareViaEmail.validations.requiredField.startButtonText"))
  });
};
var disabledTime = function disabledTime(selectedDate) {
  var current = dayjs(selectedDate).startOf("day");
  var today = dayjs().startOf("day");
  if (current.isBefore(today)) {
    return {
      disabledHours: function disabledHours() {
        return dynamicArray(24, function (i) {
          return i;
        });
      },
      disabledMinutes: function disabledMinutes() {
        return dynamicArray(60, function (i) {
          return i;
        });
      }
    };
  }
  if (current.isSame(today)) {
    var currentTime = dayjs();
    var currentHour = currentTime.hour();
    var currentMinute = currentTime.minute();
    return {
      disabledHours: function disabledHours() {
        return dynamicArray(currentHour, function (i) {
          return i;
        });
      },
      disabledMinutes: function disabledMinutes(selectedHour) {
        return selectedHour === currentHour ? 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 = useField(name),
    _useField2 = _slicedToArray(_useField, 3),
    field = _useField2[0],
    meta = _useField2[1],
    _useField2$ = _useField2[2],
    setValue = _useField2$.setValue,
    setTouched = _useField2$.setTouched;
  return /*#__PURE__*/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 = useTranslation(),
    t = _useTranslation.t;
  var _useFormikContext = useFormikContext(),
    values = _useFormikContext.values;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isAdvancedPropertiesVisible = _useState2[0],
    setIsAdvancedPropertiesVisible = _useState2[1];
  var toggleAdvancedOptions = function toggleAdvancedOptions() {
    return setIsAdvancedPropertiesVisible(not);
  };
  return /*#__PURE__*/jsxs("div", {
    className: "flex w-full flex-col items-start gap-4",
    children: [/*#__PURE__*/jsxs("button", {
      className: "flex w-full cursor-pointer items-start justify-between overflow-hidden border-0 py-4",
      type: "button",
      onClick: toggleAdvancedOptions,
      children: [/*#__PURE__*/jsx(Typography, {
        className: "flex min-w-0 flex-grow",
        component: "span",
        style: "h5",
        weight: "medium",
        children: t("neetoMolecules.shareViaEmail.advancedProperties")
      }), isAdvancedPropertiesVisible ? /*#__PURE__*/jsx(Up, {
        className: "flex-shrink-0",
        size: 20
      }) : /*#__PURE__*/jsx(Down, {
        className: "flex-shrink-0",
        size: 20
      })]
    }), isAdvancedPropertiesVisible && /*#__PURE__*/jsxs(Fragment, {
      children: [/*#__PURE__*/jsx("div", {
        children: /*#__PURE__*/jsxs(Label, {
          className: "flex items-center gap-2",
          children: [/*#__PURE__*/jsx(Switch, {
            "data-testid": "send-later-switch",
            name: "isSendLaterEnabled"
          }), /*#__PURE__*/jsx(Typography, {
            component: "span",
            "data-testid": "send-later-label",
            lineHeight: "normal",
            style: "h4",
            weight: "semibold",
            children: t("neetoMolecules.shareViaEmail.sendLater")
          })]
        })
      }), values.isSendLaterEnabled && /*#__PURE__*/jsx(FormikDatePicker, {
        autoFocus: true,
        "data-testid": "email-share-date-input",
        disabledDate: isPastDate,
        name: "sendEmailDatetime",
        size: "large"
      }), /*#__PURE__*/jsx(Input, {
        required: true,
        className: "w-full",
        label: t("neetoMolecules.shareViaEmail.startButtonText"),
        name: "actionButtonText"
      }), /*#__PURE__*/jsxs("div", {
        className: "flex w-full flex-col gap-4 sm:flex-row sm:gap-6",
        children: [showSendFromField && /*#__PURE__*/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__*/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__*/forwardRef(function (_ref, ref) {
  var id = _ref.id,
    showVideoEmbedInEditor = _ref.showVideoEmbedInEditor;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  return /*#__PURE__*/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 = useFormikContext(),
    initialValues = _useFormikContext.initialValues;
  var editorRef = useRef();
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var handleReset = function handleReset() {
    return editorRef.current.editor.commands.setContent(initialValues.emailBody);
  };
  return /*#__PURE__*/jsxs(Fragment, {
    children: [/*#__PURE__*/jsxs("div", {
      className: "flex flex-col gap-y-6",
      children: [/*#__PURE__*/jsx(SendToFields, {
        showUploadCsvButton: true,
        emailInputProps: {
          label: t("neetoMolecules.shareViaEmail.sendTo"),
          name: "notifyEmails",
          required: true
        }
      }), /*#__PURE__*/jsx(Input, {
        required: true,
        className: "col-span-1",
        label: t("neetoMolecules.shareViaEmail.subject"),
        name: "emailSubject"
      }), /*#__PURE__*/jsx(EmailBody, {
        showVideoEmbedInEditor: showVideoEmbedInEditor,
        id: "emailBody",
        ref: editorRef
      }), /*#__PURE__*/jsx("div", {
        ref: editorRef
      }), /*#__PURE__*/jsx(AdvancedProperties, {
        disableReplyTo: disableReplyTo,
        showSendFromField: showSendFromField
      })]
    }), children && /*#__PURE__*/jsxs("div", {
      className: "neeto-ui-border-gray-300 mt-4 border-t py-4",
      children: [/*#__PURE__*/jsx("h3", {
        className: "mb-4",
        children: t("neetoMolecules.shareViaEmail.additionalOptions")
      }), children]
    }), /*#__PURE__*/jsx("div", {
      className: "neeto-ui-bg-white sticky bottom-0 z-10 mt-6 py-6",
      children: /*#__PURE__*/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}}";
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 = 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__*/jsx("div", {
    className: "w-full",
    children: /*#__PURE__*/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__*/jsxs("div", {
          className: "neeto-molecules-share-frame grid grid-cols-1 md:grid-cols-12",
          children: [/*#__PURE__*/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__*/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__*/jsxs("div", {
              className: "mb-6",
              children: [/*#__PURE__*/jsx(Typography, {
                className: "mb-0.5 break-words",
                "data-testid": "share-via-email-heading",
                lineHeight: "normal",
                style: "h2",
                weight: "semibold",
                children: shareViaEmailTitle
              }), description && /*#__PURE__*/jsx(Typography, {
                className: "neeto-ui-text-gray-700",
                "data-testid": "share-via-email-sub-heading",
                lineHeight: "normal",
                style: "body2",
                children: description
              })]
            }), /*#__PURE__*/jsx(Form, {
              disableReplyTo: disableReplyTo,
              showSendFromField: showSendFromField,
              showVideoEmbedInEditor: showVideoEmbedInEditor,
              children: _children
            })]
          }), /*#__PURE__*/jsx(MobilePreviewHeader, {
            className: "col-span-1 md:hidden"
          }), /*#__PURE__*/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__*/jsx(EmailPreview, {
              actionButtonText: values.actionButtonText,
              body: values.emailBody,
              subject: values.emailSubject,
              to: sendToEmails(values.notifyEmails)
            })
          })]
        });
      }
    })
  });
};

export { ShareViaEmail as default };
//# sourceMappingURL=ShareViaEmail.js.map
