import { Host, h } from "@stencil/core";
import { getUserCart, clearUserCart } from "../../api";
import { selectedChatStore } from "../../store/store";
import { useTranslation } from "../../utils/utils";
import { openDialog, closeDialog, handleError } from "../../store/dialog";
import { ZIconButton } from "../internal-component/z-icon-button";
import { ZButton } from "../internal-component/z-button";
import { Icon } from "../internal-component/icon";
import { clearCart } from "../../utils/icon-svg";
import { getConnectionId } from "../../utils/func";
export class ProfileCartSummary {
    el;
    cartList = [];
    isLoading = false;
    disposeListener;
    prevSelectedChat = null;
    async componentWillLoad() {
        this.disposeListener = selectedChatStore.onChange('selectedChat', async (newChat) => {
            if (!newChat) {
                this.cartList = [];
                return;
            }
            if (newChat.id !== (this.prevSelectedChat ? this.prevSelectedChat.id : '')) {
                await this.loadCart();
                this.prevSelectedChat = newChat;
            }
        });
        if (selectedChatStore.get('selectedChat')) {
            await this.loadCart();
        }
    }
    disconnectedCallback() {
        if (this.disposeListener)
            this.disposeListener();
    }
    loadCart = async () => {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            return;
        const type = selectedChat.type === 'group' ? 'group' : 'user';
        if (selectedChat.connection.type !== 'zwiz' || selectedChat.type !== 'user') {
            this.cartList = [];
            return;
        }
        try {
            this.isLoading = true;
            const { channel } = selectedChat;
            const selectedChatType = selectedChat[type];
            const id = selectedChatType ? selectedChatType.id : '';
            const connectionId = getConnectionId();
            if (!connectionId) {
                return;
            }
            this.cartList = await getUserCart({
                connectionId,
                channel,
                userId: id,
            });
        }
        catch (error) {
            handleError(error, 'Failed to load Cart');
        }
        finally {
            this.isLoading = false;
        }
    };
    handleClearCart = () => {
        const t = useTranslation();
        openDialog({
            open: true,
            type: "WARNING" /* DIALOG_TYPE.WARNING */,
            title: t('chat_profile_view.clear_cart_confirmation'),
            onCloseDialog: closeDialog,
            onSubmitDialog: async () => {
                closeDialog();
                await this.executeClearCart();
            },
            buttonName: t('confirm'),
            cancelButtonName: t('cancel'),
        });
    };
    executeClearCart = async () => {
        const selectedChat = selectedChatStore.get('selectedChat');
        const { channel } = selectedChat;
        const type = selectedChat.type === 'group' ? 'group' : 'user';
        const selectedChatType = selectedChat[type];
        const id = selectedChatType ? selectedChatType.id : '';
        const connectionId = getConnectionId();
        if (!connectionId)
            return;
        try {
            this.isLoading = true;
            await clearUserCart({ connectionId, channel, userId: id });
            this.cartList = [];
        }
        catch (error) {
            handleError(error, 'Failed to clear Cart');
        }
        finally {
            this.isLoading = false;
        }
    };
    getItemTotalPrice(item) {
        return (item.price || 0) * (item.quantity || 0);
    }
    getItemTotalDiscountPrice(item) {
        return (item.discountprice || 0) * (item.quantity || 0);
    }
    get totalDiscountPrice() {
        return this.cartList.reduce((sum, item) => sum + this.getItemTotalDiscountPrice(item), 0);
    }
    formatPrice(price) {
        if (Number.isNaN(price))
            return '0';
        return new Intl.NumberFormat('th-TH', {
            style: 'currency',
            currency: 'THB',
            minimumFractionDigits: 0,
            maximumFractionDigits: 2,
        }).format(price);
    }
    render() {
        const t = useTranslation();
        const hasItems = this.cartList.length > 0;
        return (h(Host, { key: '14bf292c659fbc46e0a4cfd4271cd13ab111f081' }, h("div", { key: 'a9431963fc93460d329dab9b2c94c55f734efa21', class: "profile-cart-summary" }, h("div", { key: '5f1479f7c887753324f05421f8f82ea7e0a603e3', class: "profile-cart-summary-header" }, hasItems ? h(ZButton, { variant: "outlined", size: "small", startIcon: clearCart(), label: t('chat_profile_view.clear_cart'), onClick: this.handleClearCart }) : h(h.Fragment, null), this.isLoading ? (h(Icon, { name: "LoaderCircle", addClass: 'w-5 h-5 mr-1 text-primary animate-spin' })) : (h(ZIconButton, { variant: "text", iconName: "RotateCw", onClick: this.loadCart }))), !this.isLoading && !hasItems && (h("div", { key: '854a84a565d07ff14e6f667fa3fcb539a11ec08a', class: "profile-cart-summary-empty relative" }, h("span", { key: 'f432ea95711d39001adcc213e51f8274d4938a13', class: "text-sm" }, t('chat_profile_view.cart_empty')))), hasItems && (h("div", { key: '990dec9659363b0444fe2f8b1eb710c01a103acb', class: "profile-cart-summary-wrapper" }, h("div", { key: 'fb6e21a91e22a9502a097e12b077dbf955245b26', class: "profile-cart-summary-list" }, this.cartList.map(item => (h("div", { class: "profile-cart-summary-item" }, h("img", { src: item.photourl || '', alt: item.name, class: "profile-cart-summary-item-image", onError: (e) => (e.target.style.display = 'none') }), h("div", { class: "profile-cart-summary-item-content" }, h("div", { class: "profile-cart-summary-item-name", title: item.name }, item.name), item.option && h("div", { class: "profile-cart-summary-item-option" }, item.option)), h("div", { class: "profile-cart-summary-item-pricing" }, h("div", { class: "profile-cart-summary-item-quantity" }, "x", item.quantity), h("div", { class: "flex flex-col items-end" }, h("div", { class: "profile-cart-summary-item-price" }, this.formatPrice(this.getItemTotalDiscountPrice(item))), item.price !== item.discountprice && (h("div", { class: "text-xs text-gray-400 line-through" }, this.formatPrice(this.getItemTotalPrice(item)))))))))), h("div", { key: '3568dd8a748533ff979f36e2f7e87596aeb2552c', class: "profile-cart-summary-footer" }, h("div", { key: 'f70edaf55afa43b95a01e35eb4e874f82f097a31', class: "profile-cart-summary-total" }, h("span", { key: 'ba58b2c64e98750677277e51ce888ec0af9c3569', class: "profile-cart-summary-total-label" }, t('chat_profile_view.total_price')), h("span", { key: '6d7d02ee0f829b5dfbf9c92175e5559f1bbd2806', class: "profile-cart-summary-total-value" }, this.formatPrice(this.totalDiscountPrice)))))))));
    }
    static get is() { return "profile-cart-summary"; }
    static get originalStyleUrls() {
        return {
            "$": ["profile-cart-summary.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["profile-cart-summary.css"]
        };
    }
    static get states() {
        return {
            "cartList": {},
            "isLoading": {}
        };
    }
    static get elementRef() { return "el"; }
}
