import { h, Fragment } from "@stencil/core";
import { displayDate } from "../../utils/dayjs";
import { useTranslation } from "../../utils/utils";
import { ZIconButton } from "../internal-component/z-icon-button";
import { ZTagOrStatusItem } from "../internal-component/z-tag-or-status-item";
import { getChatPicture, handleGetUserStatuses } from "../../store/chat";
import { configStore, selectedChatStore } from "../../store/store";
import { getShopUrl, syncUser } from "../../api";
import { handleError } from "../../store/dialog";
import { shoppingCart, summarizeIcon } from "../../utils/icon-svg";
import { ZAvatarGroup } from "../internal-component/z-avatar-group";
import { ZButton } from "../internal-component/z-button";
import { Icon } from "../internal-component/icon";
import { getConnectionId } from "../../utils/func";
export class UserInfoSection {
    user;
    readOnly = false;
    isEditStatus;
    statusId;
    openDialogEditor;
    editStatus;
    closeStatus;
    removeStatus;
    saveUserStatus;
    statusSelecting;
    createUserStatusRequest;
    syncUser;
    isSyncUserLoading = false;
    isOpenShopUrlLoading = false;
    render() {
        const t = useTranslation();
        const selectedChat = selectedChatStore.get('selectedChat');
        const handleSyncUser = async (isLoadUserOnly) => {
            try {
                this.isSyncUserLoading = true;
                if (!isLoadUserOnly) {
                    const id = this.user.id;
                    const channel = this.user.channel;
                    const response = await syncUser({ channel, id });
                    if (response.code === 'user-synced') {
                        this.syncUser.emit();
                    }
                }
                else {
                    this.syncUser.emit();
                }
            }
            catch (error) {
                handleError(error, 'Failed to SyncUser');
            }
            finally {
                this.isSyncUserLoading = false;
            }
        };
        const handleOpenShopUrl = async (urlType) => {
            // const targetWindow = window.top ?? window.parent ?? window;
            const windowReference = window.open('', 'hello', urlType === 'new' ? 'width=500,height=500' : '');
            try {
                this.isOpenShopUrlLoading = true;
                const response = await getShopUrl({
                    connectionId: getConnectionId(),
                    channel: this.user.channel,
                    userId: this.user.id,
                    urlType,
                });
                if (response && response.url) {
                    if (windowReference) {
                        windowReference.location.href = response.url;
                    }
                    else {
                        window.location.href = response.url;
                    }
                }
                else {
                    windowReference?.close();
                }
            }
            catch (error) {
                windowReference?.close();
                handleError(error, 'Failed to OpenShopUrl');
            }
            finally {
                this.isOpenShopUrlLoading = false;
            }
        };
        if (!selectedChat)
            return null;
        const connection = configStore.get('connectionList').find(connection => connection.type === 'zwiz' && connection.channels.find(channel => channel.id === selectedChat?.connection?.id));
        return (h(Fragment, null, h("div", { class: "profile-info-user-tool-wrapper" }, selectedChat &&
            connection &&
            connection?.type === 'zwiz' &&
            connection?.platform === 'sme' &&
            !this.readOnly &&
            selectedChat.type === 'user' && //Hide from group chat
            h("menu-list", { referenceSelector: "profile-info-bill", icon: h(ZButton, { size: "small", label: "\u0E40\u0E1B\u0E34\u0E14\u0E1A\u0E34\u0E25", title: "\u0E40\u0E1B\u0E34\u0E14\u0E1A\u0E34\u0E25", startIcon: h(ZIconButton, { noPaddingY: true, noPadding: true, variant: "none", icon: shoppingCart(), addClassIcon: "profile-info-bill-cart-icon" }), endIcon: h(Icon, { name: "Triangle", addClass: "profile-info-bill-icon" }) }), position: "bottom-end", menuItems: [
                    {
                        label: 'เปิดบิลแบบลูกค้า',
                        value: 'normal',
                        onClick: () => handleOpenShopUrl('normal')
                    },
                    {
                        label: 'เปิดบิลแบบแอดมิน',
                        value: 'new',
                        onClick: () => handleOpenShopUrl('new')
                    },
                ], variant: "none", noPaddingY: true }), !this.readOnly &&
            selectedChat.type === 'user' &&
            h("menu-list", { referenceSelector: "profile-info-refresh", icon: h(Icon, { name: "Ellipsis", addClass: "profile-info-refresh-icon" }), position: "bottom-end", menuItems: [
                    {
                        label: 'รีเฟรช',
                        value: 'refresh',
                        onClick: () => handleSyncUser(this.user.channel === 'zignal')
                    },
                ], variant: "none", noPaddingY: true })), h("div", { class: "profile-info-user-wrapper profile-info-section-wrapper border-divider" }, h("div", { class: "profile-info-avatar-wrapper" }, h("div", { class: "profile-info-avatar-box" }, h("z-avatar", { pictureUrl: getChatPicture({
                ...selectedChat,
                user: {
                    ...selectedChat.user,
                    ...this.user
                }
            }) }), selectedChat.type === 'group' &&
            h("div", { class: "profile-info-avatar-badge" }, h(ZAvatarGroup, { size: "x-small" })))), h("div", { class: "profile-info-name-wrapper" }, h("span", { class: "text-base text-surface" }, this.user.name), h("div", { class: "profile-info-box-wrapper" }, h("span", { class: "profile-info-nickname text-surface" }, this.user.nickname || '-'), !this.readOnly && (h(ZIconButton, { variant: "text", iconName: "Pencil", addClassIcon: "size-4", onClick: () => this.openDialogEditor.emit({ label: 'Nickname', field: 'nickname', value: this.user.nickname }) }))), (() => {
            const status = this.user.status;
            if (this.isEditStatus) {
                const statusId = status ? status.id : '';
                const statusName = status ? status.name : '';
                return (h("div", { class: "profile-info-box-wrapper" }, status && statusId === this.statusId ? (h(ZTagOrStatusItem, { item: status, onDelete: () => this.removeStatus.emit() })) : (h("autocomplete-select", { value: statusId === this.statusId ? statusName : '', fetchItems: handleGetUserStatuses, createItem: name => new Promise(resolve => {
                        this.createUserStatusRequest.emit({ name, callback: resolve });
                    }), onSelecting: item => this.statusSelecting.emit(item.detail.id), referenceSelector: "profile-status" })), h(ZIconButton, { variant: "text", iconName: "X", addClassIcon: "size-4", onClick: () => this.closeStatus.emit() }), h(ZIconButton, { variant: "text", iconName: "Save", addClassIcon: "size-4", onClick: () => this.saveUserStatus.emit() })));
            }
            else {
                return (h("div", { class: "profile-info-box-wrapper" }, h("span", { class: "text-sm text-surface" }, t('status'), "\u00A0:\u00A0", status ? (h("tag-or-status-item", { item: status, chatId: `profile-status-${selectedChat.id}-${this.readOnly ? 'readonly' : ''}` })) : ('-')), !this.readOnly && h(ZIconButton, { variant: "text", iconName: "Pencil", addClassIcon: "size-4", onClick: () => this.editStatus.emit() })));
            }
        })()), this.user.summarized_message && (h("div", { class: "col-span-3" }, h("div", { class: "profile-info-summarize-wrapper" }, h("span", { class: "profile-info-box-wrapper text-surface" }, t('profile_tab.ai_summary'), summarizeIcon()), h("span", { class: "text-xs text-theme-gray" }, t('profile_tab.last_update'), " ", displayDate(this.user.summarized_message.created_at))), h("div", { class: "profile-info-summarize-text" }, h("typography-clamp", { text: this.user.summarized_message.text })))))));
    }
    static get is() { return "user-info-section"; }
    static get originalStyleUrls() {
        return {
            "$": ["profile-info.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["profile-info.css"]
        };
    }
    static get properties() {
        return {
            "user": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "UserItem",
                    "resolved": "{ id: string; channel: ChannelType; user_id?: string; picture_url?: string; name: string; nickname: string; email?: string | string[]; phone_number?: string | string[]; address?: UserAddress; gender?: string; locale: string; note?: string; status?: TTagOrStatusItem; tags: TTagOrStatusItem[]; last_active_at: Date; created_at: Date; created_by: string; last_updated_at: Date; last_updated_by: string; summarized_message?: UserSummarizedMessage; match_users?: MatchUserItem[]; zignal_user_id?: string; associated_users?: AssociatedUser[]; context?: string; summarize_messages: TTagOrStatusItem[]; session?: UserSession; }",
                    "references": {
                        "UserItem": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::UserItem",
                            "referenceLocation": "UserItem"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "readOnly": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "read-only",
                "defaultValue": "false"
            },
            "isEditStatus": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-edit-status"
            },
            "statusId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "status-id"
            }
        };
    }
    static get states() {
        return {
            "isSyncUserLoading": {},
            "isOpenShopUrlLoading": {}
        };
    }
    static get events() {
        return [{
                "method": "openDialogEditor",
                "name": "openDialogEditor",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ label: string; field: string; value: string }",
                    "resolved": "{ label: string; field: string; value: string; }",
                    "references": {}
                }
            }, {
                "method": "editStatus",
                "name": "editStatus",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "closeStatus",
                "name": "closeStatus",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "removeStatus",
                "name": "removeStatus",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "saveUserStatus",
                "name": "saveUserStatus",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "statusSelecting",
                "name": "statusSelecting",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                }
            }, {
                "method": "createUserStatusRequest",
                "name": "createUserStatusRequest",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ name: string; callback: (value: TTagOrStatusItem) => void }",
                    "resolved": "{ name: string; callback: (value: TTagOrStatusItem) => void; }",
                    "references": {
                        "TTagOrStatusItem": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::TTagOrStatusItem",
                            "referenceLocation": "TTagOrStatusItem"
                        }
                    }
                }
            }, {
                "method": "syncUser",
                "name": "syncUser",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
}
