"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
module.exports = PromotionCode;
var _jsxRuntime = require("react/jsx-runtime");
var _context = require("@arcblock/ux/lib/Locale/context");
var _material = require("@mui/material");
var _iconsMaterial = require("@mui/icons-material");
var _react = require("react");
var _loadingButton = _interopRequireDefault(require("./loading-button"));
var _api = _interopRequireDefault(require("../libs/api"));
var _payment = require("../contexts/payment");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function PromotionCode({
  checkoutSessionId,
  initialAppliedCodes = [],
  disabled = false,
  className = "",
  placeholder = "",
  onUpdate = void 0,
  currencyId
}) {
  const {
    t
  } = (0, _context.useLocaleContext)();
  const [showInput, setShowInput] = (0, _react.useState)(false);
  const [code, setCode] = (0, _react.useState)("");
  const [error, setError] = (0, _react.useState)("");
  const [applying, setApplying] = (0, _react.useState)(false);
  const [appliedCodes, setAppliedCodes] = (0, _react.useState)(initialAppliedCodes);
  const {
    session,
    paymentState
  } = (0, _payment.usePaymentContext)();
  const handleLoginCheck = () => {
    if (!session.user) {
      session?.login(() => {
        handleApply();
      });
    } else {
      handleApply();
    }
  };
  const handleApply = async () => {
    if (!code.trim()) return;
    if (paymentState.paying || paymentState.stripePaying) {
      return;
    }
    setApplying(true);
    setError("");
    try {
      const response = await _api.default.post(`/api/checkout-sessions/${checkoutSessionId}/apply-promotion`, {
        promotion_code: code.trim(),
        currency_id: currencyId
      });
      const discounts = response.data.discounts || [];
      const appliedDiscount = discounts[0];
      if (appliedDiscount) {
        const newCode = {
          id: appliedDiscount.promotion_code || appliedDiscount.coupon,
          code: code.trim(),
          discount_amount: appliedDiscount.discount_amount
        };
        setAppliedCodes([newCode]);
        setCode("");
        setShowInput(false);
        onUpdate?.({
          appliedCodes: [newCode],
          discountAmount: appliedDiscount.discount_amount
        });
      }
    } catch (err) {
      const errorMessage = err.response?.data?.error || err.message;
      setError(errorMessage);
    } finally {
      setApplying(false);
    }
  };
  const handleKeyPress = event => {
    if (event.key === "Enter" && !applying && code.trim()) {
      handleLoginCheck();
    }
  };
  const isPaymentInProgress = paymentState.paying || paymentState.stripePaying;
  return /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Box, {
    className,
    children: appliedCodes.length === 0 && !disabled && !isPaymentInProgress && (showInput ? /* @__PURE__ */(0, _jsxRuntime.jsxs)(_material.Box, {
      onBlur: () => {
        if (!code.trim()) {
          setShowInput(false);
        }
      },
      children: [/* @__PURE__ */(0, _jsxRuntime.jsx)(_material.TextField, {
        fullWidth: true,
        value: code,
        onChange: e => setCode(e.target.value),
        onKeyPress: handleKeyPress,
        placeholder: placeholder || t("payment.checkout.promotion.placeholder"),
        variant: "outlined",
        size: "small",
        disabled: applying,
        autoFocus: true,
        slotProps: {
          input: {
            endAdornment: /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.InputAdornment, {
              position: "end",
              children: /* @__PURE__ */(0, _jsxRuntime.jsx)(_loadingButton.default, {
                size: "small",
                onClick: handleLoginCheck,
                loading: applying,
                disabled: !code.trim(),
                variant: "text",
                sx: {
                  color: "primary.main",
                  fontSize: "small"
                },
                children: t("payment.checkout.promotion.apply")
              })
            })
          }
        },
        sx: {
          "& .MuiOutlinedInput-root": {
            pr: 1
          }
        }
      }), error && /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Alert, {
        severity: "error",
        sx: {
          my: 1
        },
        children: error
      })]
    }) : /* @__PURE__ */(0, _jsxRuntime.jsx)(_material.Button, {
      onClick: () => setShowInput(true),
      startIcon: /* @__PURE__ */(0, _jsxRuntime.jsx)(_iconsMaterial.Add, {
        fontSize: "small"
      }),
      variant: "text",
      sx: {
        fontWeight: "normal",
        textTransform: "none",
        justifyContent: "flex-start",
        p: 0,
        "&:hover": {
          backgroundColor: "transparent",
          textDecoration: "underline"
        }
      },
      children: t("payment.checkout.promotion.add_code")
    }))
  });
}