"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.AccountDetailsCardsPage = void 0;
const contexts_1 = require("../../../contexts/index.js");
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const react_router_dom_1 = require("react-router-dom");
const Fade_1 = __importDefault(require("../../../animations/Fade"));
const MembersServiceAPI_1 = require("../../../api/members-service/MembersServiceAPI");
const BEButton_1 = __importDefault(require("../../../components/generic/BEButton"));
const Headline_1 = __importDefault(require("../../../components/generic/Headline"));
const Icon_1 = require("../../../components/generic/Icon/Icon");
const LargeLoader_1 = __importDefault(require("../../../components/generic/loader/LargeLoader"));
const PaymentCardInput_1 = require("../../../components/generic/PaymentCard/PaymentCardInput");
const Text_1 = __importDefault(require("../../../components/generic/Text"));
const CardList_1 = require("../../../components/pages/Account/Card/CardList");
const AccountDetailsNoCardsPage_1 = require("./AccountDetailsNoCardsPage");
const Translation_1 = require("../../../translations/Translation");
const AccountDetailsCardsPage_module_scss_1 = __importDefault(require("./AccountDetailsCardsPage.module.scss"));
const AccountDetailsCardsPage = (ref) => {
    var _a, _b;
    const { roomstayMember, cards: memberCards = [], updateCardToMemberDetail, fetchRoomstayMember, updateMemberDetails, loading } = (0, react_1.useContext)(contexts_1.RoomstayMemberContext);
    const emptyCard = (0, react_1.useMemo)(() => ({
        cardId: '',
        cardNumber: '',
        expiry: '',
        name: '',
        securityCode: '',
        type: '',
        username: (roomstayMember === null || roomstayMember === void 0 ? void 0 : roomstayMember.username) || '',
    }), [roomstayMember]);
    const { t } = (0, react_i18next_1.useTranslation)();
    const [selectedCard, setSelectedCard] = (0, react_1.useState)(emptyCard);
    const [isAddingCard, setIsAddingCard] = (0, react_1.useState)(!!((_a = roomstayMember === null || roomstayMember === void 0 ? void 0 : roomstayMember.cards) === null || _a === void 0 ? void 0 : _a.length));
    (0, react_1.useEffect)(() => {
        var _a;
        if ((_a = roomstayMember === null || roomstayMember === void 0 ? void 0 : roomstayMember.cards) === null || _a === void 0 ? void 0 : _a.length) {
            setIsAddingCard(true);
        }
    }, [(_b = roomstayMember === null || roomstayMember === void 0 ? void 0 : roomstayMember.cards) === null || _b === void 0 ? void 0 : _b.length]);
    (0, react_1.useEffect)(() => {
        const existedCard = memberCards.find((card) => card.cardId === selectedCard.cardId);
        if (!existedCard) {
            if (memberCards.length)
                setSelectedCard(memberCards[0]);
            else
                setSelectedCard(emptyCard);
        }
    }, [roomstayMember, memberCards === null || memberCards === void 0 ? void 0 : memberCards.length]);
    const onNewCardClicked = () => {
        setSelectedCard(emptyCard);
    };
    const onCardChangedSubmit = (card) => __awaiter(void 0, void 0, void 0, function* () {
        // TODO: Add loading
        if (!card.cardId) {
            return (0, MembersServiceAPI_1.AddMemberCard)(card).then((newCard) => {
                setSelectedCard(Object.assign(Object.assign({}, card), newCard));
                updateCardToMemberDetail === null || updateCardToMemberDetail === void 0 ? void 0 : updateCardToMemberDetail(newCard);
                return newCard;
            });
        }
        else
            return (0, MembersServiceAPI_1.EditMemberCard)(card).then((res) => {
                setSelectedCard(card);
                updateCardToMemberDetail === null || updateCardToMemberDetail === void 0 ? void 0 : updateCardToMemberDetail(res);
                return res;
            });
    });
    const onDeleteClicked = (card) => __awaiter(void 0, void 0, void 0, function* () {
        try {
            yield (0, MembersServiceAPI_1.DeleteMemberCard)(card);
            yield (fetchRoomstayMember === null || fetchRoomstayMember === void 0 ? void 0 : fetchRoomstayMember());
        }
        catch (ex) {
            console.log('Failed deleting card');
        }
    });
    const onMarkedAsDefault = (card) => __awaiter(void 0, void 0, void 0, function* () {
        yield (updateMemberDetails === null || updateMemberDetails === void 0 ? void 0 : updateMemberDetails(Object.assign(Object.assign({}, roomstayMember), { defaultCard: card === null || card === void 0 ? void 0 : card.cardId })));
        setSelectedCard(card);
    });
    if (loading)
        return react_1.default.createElement(LargeLoader_1.default, null);
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: "u-marg-top--heavy@m u-marg-top@m- u-marg-bottom--heavy" },
            react_1.default.createElement(react_router_dom_1.Link, { to: "/account/home" },
                react_1.default.createElement(BEButton_1.default, { isText: true, icon: Icon_1.IconType.ArrowLeft, size: "small" }, t(Translation_1.Translation.Reservation.BackToYourAccount)))),
        react_1.default.createElement("div", { className: "u-marg-bottom--heavy@m" },
            react_1.default.createElement(Headline_1.default, { size: "extra-large", bold: true }, t(Translation_1.Translation.Navigation.Menu.PaymentInformation))),
        react_1.default.createElement(Fade_1.default, { open: isAddingCard },
            react_1.default.createElement("div", { className: AccountDetailsCardsPage_module_scss_1.default['layout-grid'] },
                react_1.default.createElement("div", { className: AccountDetailsCardsPage_module_scss_1.default['card-list'] },
                    react_1.default.createElement(Text_1.default, { bold: true, className: "u-marg-bottom" }, t(Translation_1.Translation.UserPortal.PaymentInformationScreen.SavedCards)),
                    react_1.default.createElement(CardList_1.CardList, { onNewCardClicked: onNewCardClicked, value: selectedCard, onChange: (selectedCard) => setSelectedCard(selectedCard), options: memberCards })),
                react_1.default.createElement(PaymentCardInput_1.PaymentCardInput, { card: selectedCard, onSubmit: onCardChangedSubmit, onDeleteClicked: onDeleteClicked, onMarkedAsDefaultClicked: onMarkedAsDefault }))),
        !isAddingCard && react_1.default.createElement(AccountDetailsNoCardsPage_1.AccountDetailsNoCardsPage, { onAddNewCard: () => setIsAddingCard(true) })));
};
exports.AccountDetailsCardsPage = AccountDetailsCardsPage;
//# sourceMappingURL=AccountDetailsCardsPage.js.map