"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

exports.__esModule = true;
exports.Checkout = void 0;

var _taggedTemplateLiteralLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteralLoose"));

var _react = _interopRequireWildcard(require("react"));

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _router = require("next/router");

var _lib = require("@sentecacommerce-theme/lib");

var _Components = require("./Components");

var _Icons = require("../Common/Icons");

var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7;

var Checkout = function Checkout(_ref) {
  var labels = _ref.labels,
      errors = _ref.errors;

  var _useState = (0, _react.useState)(),
      email = _useState[0],
      setEmail = _useState[1];

  var _useBoolean = (0, _lib.useBoolean)(),
      gdprAgreed = _useBoolean[0],
      setGdprAgreed = _useBoolean[1];

  var _useBulkSubscribe = (0, _lib.useBulkSubscribe)({}),
      subscribe = _useBulkSubscribe[0];

  var _useAllSubscriptions = (0, _lib.useAllSubscriptions)({
    tag: 'checkout'
  }),
      requiredSubs = _useAllSubscriptions.requiredSubs;

  var router = (0, _router.useRouter)();

  var _useState2 = (0, _react.useState)(false),
      isRedirecting = _useState2[0],
      setIsRedirecting = _useState2[1];

  var onSuccess = function onSuccess(_ref2) {
    var _id = _ref2._id;
    router.push("/order/" + _id + "?success=true");
  };

  var onError = function onError(error) {
    console.log('error');
    console.log(error);
  };

  var onSubmit = function onSubmit(data) {
    var isShippingValid = data.isShippingValid,
        setIsShippingSubmitting = data.setIsShippingSubmitting,
        isBillingValid = data.isBillingValid,
        setIsBillingSubmitting = data.setIsBillingSubmitting,
        isPaymentValid = data.isPaymentValid,
        setIsPaymentSubmitting = data.setIsPaymentSubmitting,
        step = data.step,
        updateStep = data.updateStep,
        saveOrder = data.saveOrder,
        scrollToFirstError = data.scrollToFirstError;
    scrollToFirstError();
    setIsShippingSubmitting(true);
    setIsBillingSubmitting(true); // exit if shipping or billing is not valid

    if (!isShippingValid || !isBillingValid) {
      setGdprAgreed.off();

      if (step !== _lib.CheckoutFormStepsEnum.Shipping) {
        updateStep(_lib.CheckoutFormStepsEnum.Shipping);
        return;
      }

      return;
    }
    /**
     * edge case:
     * user is not on 2nd step and the shipping or billing data is
     * not valid anymore
     */
    // Go to payment after shipping and billing data is valid


    if (step === _lib.CheckoutFormStepsEnum.Shipping) {
      updateStep(_lib.CheckoutFormStepsEnum.Payment);
      return;
    } // Set payment as submitting


    setIsPaymentSubmitting(true);

    if (!isPaymentValid) {
      /**
       * edge case:
       * user is not on 3nd step and the shipping or billing data is
       * not valid anymore
       */
      // if (
      //   step !== CheckoutFormStepsEnum.Shipping &&
      //   step !== CheckoutFormStepsEnum.Payment
      // ) {
      //   updateStep(CheckoutFormStepsEnum.Payment)
      // }
      return;
    }

    if (!gdprAgreed) {
      // If somehow click submit without checking the agreements
      return;
    } // send order if everything is valid


    subscribe({
      email: email,
      consentKeys: requiredSubs
    });
    saveOrder();
  };

  var _useConfigState = (0, _lib.useConfigState)(),
      countryCode = _useConfigState.countryCode;

  return /*#__PURE__*/_react["default"].createElement(_lib.LocalLabelsProvider, {
    labels: labels
  }, /*#__PURE__*/_react["default"].createElement(_lib.CheckoutFormContextProvider, {
    errorLabels: errors,
    defaultStep: _lib.CheckoutFormStepsEnum.Shipping,
    onSubmit: onSubmit,
    countryCode: countryCode,
    withPersistBeforePageLeave: true,
    enableSaveAddress: true,
    enableSavedAddressList: true,
    autofillShippingPersonalData: true,
    autoSelectDefaultShippingAddress: true,
    enableSaveBillingAddress: true,
    enableSavedBillingAddressList: true,
    autoSelectDefaultBillingAddress: true,
    shippingEnabledOnStep: _lib.CheckoutFormStepsEnum.Shipping,
    billingEnabledOnStep: _lib.CheckoutFormStepsEnum.Shipping,
    paymentEnabledOnStep: _lib.CheckoutFormStepsEnum.Payment,
    onSuccess: onSuccess,
    onError: onError,
    onBeforeRedirect: function onBeforeRedirect() {
      return setIsRedirecting(true);
    },
    withPixelMeta: true
  }, /*#__PURE__*/_react["default"].createElement(Background, null, /*#__PURE__*/_react["default"].createElement(Container, null, /*#__PURE__*/_react["default"].createElement("div", {
    className: "pb-4 d-flex align-items-center px-4 justify-content-between"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "d-flex align-items-center"
  }, /*#__PURE__*/_react["default"].createElement(_lib.Link, {
    href: "/",
    passHref: true
  }, /*#__PURE__*/_react["default"].createElement(IconContainer, null, /*#__PURE__*/_react["default"].createElement(_Icons.IconDistrictLogoNew, null)))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "pr-4 d-none d-lg-block"
  }, /*#__PURE__*/_react["default"].createElement(PhoneIconContainer, null, /*#__PURE__*/_react["default"].createElement(_Icons.IconPhone, null)), /*#__PURE__*/_react["default"].createElement("span", null, labels.questionsLabel), /*#__PURE__*/_react["default"].createElement(PhoneNumber, null, labels.phoneNumberLabel), /*#__PURE__*/_react["default"].createElement("span", {
    className: "pl-3"
  }, labels.workTimeLabel)))), /*#__PURE__*/_react["default"].createElement(_Components.CheckoutHeader, null), /*#__PURE__*/_react["default"].createElement(Line, null), /*#__PURE__*/_react["default"].createElement(Container, null, !isRedirecting && /*#__PURE__*/_react["default"].createElement("div", {
    className: "row"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "col-12 col-lg-8"
  }, /*#__PURE__*/_react["default"].createElement(_Components.CheckoutSteps, null)), /*#__PURE__*/_react["default"].createElement("aside", {
    className: "col-12 col-lg-4"
  }, /*#__PURE__*/_react["default"].createElement(BoxContainer, {
    active: true
  }, /*#__PURE__*/_react["default"].createElement(_Components.OrderSummary, {
    title: labels.summaryTitle,
    setEmail: setEmail,
    gdprAgreed: gdprAgreed,
    checkGDPR: function checkGDPR() {
      return setGdprAgreed.on();
    },
    uncheckGDPR: function uncheckGDPR() {
      return setGdprAgreed.off();
    }
  })))), isRedirecting && /*#__PURE__*/_react["default"].createElement("div", null, labels.redirecting)), /*#__PURE__*/_react["default"].createElement(_Components.BasketItemsWithErrorsModal, null))));
};

exports.Checkout = Checkout;

var Background = _styledComponents["default"].div.attrs({
  className: 'pb-4 pt-3'
})(_templateObject || (_templateObject = (0, _taggedTemplateLiteralLoose2["default"])(["\n  @media (max-width: ", ") {\n    overflow: hidden;\n  }\n  max-width: 100vw;\n"])), function (_ref3) {
  var theme = _ref3.theme;
  return theme.breakpoints.md.max;
});

var IconContainer = _styledComponents["default"].a.attrs({
  className: 'd-flex '
})(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  cursor: pointer;\n  margin-left: -2rem;\n  &:hover {\n    opacity: 0.7;\n  }\n"])));

var PhoneIconContainer = _styledComponents["default"].a.attrs({
  className: 'mr-2'
})(_templateObject3 || (_templateObject3 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  & > svg {\n    position: relative;\n    top: 0.5rem;\n  }\n"])));

var PhoneNumber = _styledComponents["default"].span.attrs({
  className: 'pl-2'
})(_templateObject4 || (_templateObject4 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  text-decoration: underline;\n"])));

var BoxContainer = _styledComponents["default"].div.attrs({
  className: 'px-4'
})(_templateObject5 || (_templateObject5 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  display: ", ";\n  @media (min-width: ", ") {\n    position: sticky;\n    top: 0;\n  }\n"])), function (props) {
  return props.active ? 'block' : 'none';
}, function (_ref4) {
  var theme = _ref4.theme;
  return theme.breakpoints.lg.min;
});

var Container = _styledComponents["default"].div.attrs({
  className: 'mx-auto'
})(_templateObject6 || (_templateObject6 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  max-width: 120rem;\n  width: 100%;\n"])));

var Line = _styledComponents["default"].div(_templateObject7 || (_templateObject7 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  height: 0.1rem;\n  width: 100%;\n  background-color: ", ";\n"])), function (_ref5) {
  var theme = _ref5.theme;
  return theme.palette.light;
});
//# sourceMappingURL=checkout.component.js.map