import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { globalProps } from '@bigbinary/neeto-commons-frontend/initializers';
import { withT, useDisplayErrorPage } from '@bigbinary/neeto-commons-frontend/react-utils';
import ErrorPageGlobal from '@bigbinary/neeto-molecules/ErrorPage';
import PageLoader from '@bigbinary/neeto-molecules/PageLoader';
import Typography from '@bigbinary/neetoui/Typography';
import Input from '@bigbinary/neetoui/formik/Input';
import Form from '@bigbinary/neetoui/formik/Form';
import ActionBlock from '@bigbinary/neetoui/formik/ActionBlock';
import { Trans, useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
import { S as SvgInviteLinkError, u as useShowInviteLink, a as useCreateInvitation } from './InviteLinkError-5auG6HEb.js';
import { Q as QUERY_KEYS } from './constants-CXdiW8NZ.js';
import { t } from 'i18next';
import { SINGULAR } from '@bigbinary/neeto-commons-frontend/constants';
import * as yup from 'yup';
import { jsx, jsxs } from 'react/jsx-runtime';
import { dayjs } from '@bigbinary/neeto-commons-frontend/utils';
import '@babel/runtime/helpers/defineProperty';
import 'axios';

var VALIDATION_SCHEMA = yup.object().shape({
  email: yup.string().email(t("neetoTeamMembers.validations.validEmail_one")).required(t("neetoTeamMembers.validations.required", {
    what: t("neetoTeamMembers.common.email", SINGULAR)
  }))
});
var ERROR = {
  EXPIRED: 410,
  INVALID_DOMAIN: 422
};
var ROOT_URL = "/";

var ErrorPage = withT(function (_ref) {
  var t = _ref.t,
    _ref$isExpired = _ref.isExpired,
    isExpired = _ref$isExpired === void 0 ? false : _ref$isExpired,
    _ref$email = _ref.email,
    email = _ref$email === void 0 ? "" : _ref$email,
    _ref$allowedDomain = _ref.allowedDomain,
    allowedDomain = _ref$allowedDomain === void 0 ? "" : _ref$allowedDomain;
  return /*#__PURE__*/jsx("div", {
    className: "flex justify-center items-center min-h-screen bg-gray-50 px-4 h-screen w-screen",
    children: /*#__PURE__*/jsxs("div", {
      className: "w-full max-w-2xl text-center space-y-4 flex flex-col items-center justify-center",
      children: [/*#__PURE__*/jsx("div", {
        className: "mb-4",
        children: /*#__PURE__*/jsx(SvgInviteLinkError, {
          size: 64
        })
      }), /*#__PURE__*/jsx(Typography, {
        style: "h1",
        weight: "bold",
        children: isExpired ? t("neetoTeamMembers.alerts.messages.expiredTitle") : t("neetoTeamMembers.alerts.messages.domainTitle")
      }), /*#__PURE__*/jsx(Typography, {
        className: "neeto-ui-text-gray-600",
        children: isExpired ? t("neetoTeamMembers.alerts.messages.expiredMessage") : /*#__PURE__*/jsx(Trans, {
          components: {
            strong: /*#__PURE__*/jsx("strong", {})
          },
          i18nKey: "neetoTeamMembers.alerts.messages.domainMessage",
          values: {
            allowedDomain: allowedDomain,
            email: email
          }
        })
      })]
    })
  });
});

var getStartOfDay = function getStartOfDay(date) {
  return dayjs(date).startOf("day");
};
var isExpired = function isExpired(date) {
  if (!date) return false;
  var today = getStartOfDay();
  var expiryDate = getStartOfDay(date);
  return expiryDate.isSameOrBefore(today);
};

var MembersInvite = function MembersInvite() {
  var queryClient = useQueryClient();
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useParams = useParams(),
    inviteId = _useParams.inviteId;
  var displayErrorPage = useDisplayErrorPage();
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isSubmitting = _useState2[0],
    setIsSubmitting = _useState2[1];
  var _useShowInviteLink = useShowInviteLink(inviteId),
    inviteLink = _useShowInviteLink.data,
    isLoading = _useShowInviteLink.isLoading;
  var handleSuccess = function handleSuccess(response) {
    if (response !== null && response !== void 0 && response.redirectUrl) {
      window.location.href = response.redirectUrl;
    } else {
      setIsSubmitting(false);
    }
  };
  var handleError = function handleError() {
    queryClient.invalidateQueries({
      queryKey: [QUERY_KEYS.INVITATION_LINK, inviteId]
    });
    setIsSubmitting(false);
  };
  var _useCreateInvitation = useCreateInvitation({
      onSuccess: handleSuccess,
      onError: handleError
    }),
    createInvitation = _useCreateInvitation.mutate,
    isError = _useCreateInvitation.isError,
    error = _useCreateInvitation.error,
    variables = _useCreateInvitation.variables;
  var isInviteExpired = isExpired(inviteLink === null || inviteLink === void 0 ? void 0 : inviteLink.expiresAt) || isError && (error === null || error === void 0 ? void 0 : error.status) === ERROR.EXPIRED;
  var isInvalidDomain = isError && (error === null || error === void 0 ? void 0 : error.status) === ERROR.INVALID_DOMAIN;
  var handleSubmit = function handleSubmit(_ref) {
    var email = _ref.email;
    setIsSubmitting(true);
    return createInvitation({
      email: email,
      inviteToken: inviteId
    });
  };
  if (isLoading || isSubmitting) {
    return /*#__PURE__*/jsx("div", {
      className: "h-screen w-screen",
      children: /*#__PURE__*/jsx(PageLoader, {})
    });
  }
  if (isInviteExpired || isInvalidDomain) {
    return /*#__PURE__*/jsx(ErrorPage, {
      allowedDomain: inviteLink === null || inviteLink === void 0 ? void 0 : inviteLink.domain,
      email: variables === null || variables === void 0 ? void 0 : variables.email,
      isExpired: isInviteExpired
    });
  }
  if (displayErrorPage) {
    return /*#__PURE__*/jsx(ErrorPageGlobal, {
      homeUrl: ROOT_URL
    });
  }
  return /*#__PURE__*/jsx("div", {
    className: "flex justify-center items-center min-h-screen bg-gray-50 px-4 w-screen",
    children: /*#__PURE__*/jsxs("div", {
      className: "w-full max-w-md p-6 space-y-6 neeto-ui-shadow-lg",
      children: [/*#__PURE__*/jsxs("div", {
        className: "text-center space-y-2",
        children: [/*#__PURE__*/jsx(Typography, {
          style: "h3",
          children: t("neetoTeamMembers.helpers.invitationTitle")
        }), /*#__PURE__*/jsx(Typography, {
          className: "neeto-ui-text-gray-600",
          style: "body2",
          children: /*#__PURE__*/jsx(Trans, {
            components: {
              strong: /*#__PURE__*/jsx("strong", {})
            },
            i18nKey: "neetoTeamMembers.helpers.invitationMessage",
            values: {
              organization: globalProps.organization.name
            }
          })
        })]
      }), /*#__PURE__*/jsx(Form, {
        formikProps: {
          initialValues: {
            email: ""
          },
          validationSchema: VALIDATION_SCHEMA,
          onSubmit: handleSubmit
        },
        children: function children(_ref2) {
          var isValid = _ref2.isValid,
            dirty = _ref2.dirty;
          return /*#__PURE__*/jsxs("div", {
            className: "space-y-4",
            children: [/*#__PURE__*/jsx(Input, {
              required: true,
              label: t("neetoTeamMembers.common.email_one"),
              name: "email",
              type: "email"
            }), /*#__PURE__*/jsx(ActionBlock, {
              submitButtonProps: {
                label: t("neetoTeamMembers.buttons.acceptInvitation"),
                disabled: !isValid || !dirty
              }
            })]
          });
        }
      })]
    })
  });
};

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