"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromotionalCodeInput = void 0;
const contexts_1 = require("../../contexts/index.js");
const ui_1 = require("@roomstay/ui");
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const AutoAutoHeight_1 = __importDefault(require("../../animations/AutoAutoHeight"));
const Alert_1 = __importStar(require("./Alert"));
const BEButton_1 = __importDefault(require("./BEButton"));
const Text_1 = __importStar(require("./Text"));
const TextBox_1 = __importDefault(require("./TextBox"));
const useNextStepAction_1 = require("../../hooks/useNextStepAction");
const Translation_1 = require("../../translations/Translation");
const PromotionalWarnings = ({ promoCode, isSubmitted, rows }) => {
    const { t } = (0, react_i18next_1.useTranslation)();
    if (!isSubmitted)
        return react_1.default.createElement(react_1.default.Fragment, null);
    // Collect unique promo code warnings from all rows
    const errors = Array.from(new Set(rows.flatMap((row) => row.getPromoCodeWarningMessage() || [])));
    // Start with checking if the input promo code is non-empty and there are no initial warnings
    let isValid = !!promoCode.trim() && errors.length === 0;
    // If there are no errors from the API, validate each row in the basket
    if (!errors.length) {
        // A row is valid if it has a rate and the promo applies to it
        const rowHasValidPromo = (row) => {
            var _a;
            const rate = row.getRate();
            if (!rate)
                return false;
            const promo = (_a = row.getPromoCode()) === null || _a === void 0 ? void 0 : _a.trim();
            return promo && rate.getTotalDiscount() > 0;
        };
        const appliesToAtLeastOneRow = rows.some(rowHasValidPromo);
        if (!appliesToAtLeastOneRow) {
            const message = t(Translation_1.Translation.Step.Confirmation.Inputs.PromotionalCodeValidation.NotLinkedToRate);
            if (!errors.includes(message)) {
                errors.push(message);
            }
            isValid = false;
        }
    }
    if (isValid) {
        return (react_1.default.createElement("div", { className: "rs-promotional-code-warnings u-flex u-marg-top u-marg-bottom align-items-center u-flex-col" },
            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, color: ui_1.Color.Success }, t(Translation_1.Translation.Step.Confirmation.Inputs.PromotionalCodeValidation.Valid, {
                value: promoCode,
            }))));
    }
    if (!errors.length)
        return react_1.default.createElement(react_1.default.Fragment, null);
    return (react_1.default.createElement("div", { className: "rs-promotional-code-warnings u-flex u-marg-top u-marg-bottom align-items-center u-flex-col" }, errors.map((error, i) => (react_1.default.createElement(AutoAutoHeight_1.default, { key: i, open: true },
        react_1.default.createElement("div", { className: "u-flex" },
            react_1.default.createElement(Alert_1.default, { icon: ui_1.IconType.Error, type: Alert_1.AlertType.Danger },
                react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small }, error))))))));
};
const PromotionalCodeInput = () => {
    const { t } = (0, react_i18next_1.useTranslation)();
    const context = (0, react_1.useContext)(contexts_1.BasketContext);
    const { syncBasketRowUnMatchedPrice } = (0, useNextStepAction_1.useNextStepAction)();
    const [promoCode, setPromoCode] = (0, react_1.useState)('');
    const [isSubmitted, setIsSubmitted] = (0, react_1.useState)(false);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const handleChange = (e) => {
        setPromoCode(e.target.value);
        setIsSubmitted(false);
    };
    const handleKeyPress = (event) => {
        if (event.key === 'Enter')
            handleSubmit();
    };
    const handleSubmit = () => __awaiter(void 0, void 0, void 0, function* () {
        try {
            setIsSubmitted(false);
            context.currentBasketRows.forEach((row) => {
                row.setPromoCode(promoCode);
                context.updateBasketRow(row);
            });
            setIsLoading(true);
            yield syncBasketRowUnMatchedPrice();
        }
        finally {
            setIsLoading(false);
            setIsSubmitted(true);
        }
    });
    return (react_1.default.createElement("div", { className: "rs-promotional-code" },
        react_1.default.createElement("label", { className: "u-marg-bottom--lighter text-bold d-flex" }, t(Translation_1.Translation.Step.Confirmation.Inputs.PromotionalCode)),
        react_1.default.createElement("div", { className: "d-flex flex-wrap justify-content-space-between align-items-center" },
            react_1.default.createElement("div", { className: "u-marg-right--light u-flex__item" },
                react_1.default.createElement(TextBox_1.default, { className: "rs-promotional-code-input", value: promoCode.toUpperCase(), placeholder: t(Translation_1.Translation.Step.Confirmation.Inputs.PromotionalCodePlaceHolder), onChange: handleChange, onKeyPress: handleKeyPress, wide: true })),
            react_1.default.createElement("div", { className: "rs-promotional-code-submit-btn d-flex justify-content-center align-items-center" },
                react_1.default.createElement(BEButton_1.default, { disabled: isLoading, rounded: true, filled: true, primary: true, size: "small", onClick: handleSubmit, isLoading: isLoading }, t(Translation_1.Translation.Misc.Apply)))),
        react_1.default.createElement("span", { className: "text-small promotional-code-description" }, t(Translation_1.Translation.Step.Confirmation.Inputs.PromotionalCodeDescription)),
        react_1.default.createElement(PromotionalWarnings, { promoCode: promoCode, isSubmitted: isSubmitted, rows: context.currentBasketRows })));
};
exports.PromotionalCodeInput = PromotionalCodeInput;
//# sourceMappingURL=PromotionalCodeInput.js.map