import { Host, h, Fragment } from "@stencil/core";
import { businessStore, configStore, deviceModeStore, profilePanelStore, selectedChatStore, userInfosStore } from "../../store/store";
import { ZIconButton } from "../internal-component/z-icon-button";
import { useTranslation } from "../../utils/utils";
import { getUserToken, getZwizCheckBotPage } from "../../api";
import { handleError } from "../../store/dialog";
import { getConnectionId, getConnectionItem, getZwizPackageData, getZwizPackageType } from "../../utils/func";
import { getBusinessGroups, getBusinessUsers, getProfile } from "../../api/zdesk/business";
import { getTicketStatusSetting } from "../../api/zdesk/ticket";
import { Icon } from "../internal-component/icon";
export class ProfileTabs {
    firstTab = 'info';
    active = this.firstTab;
    renderedTabs = new Set([this.firstTab]);
    chatId = '';
    isLoading = false;
    canScrollLeft = false;
    canScrollRight = false;
    scrollContainer;
    resizeObserver;
    disposeSelectedChatListener;
    disposeProfilePanelListener;
    prevChatId = null;
    lastActive = '';
    async componentWillLoad() {
        const selectedChat = selectedChatStore.get('selectedChat');
        this.chatId = selectedChat?.id || '';
        this.prevChatId = selectedChat?.id || null;
        await this.initialize(selectedChat);
        this.disposeSelectedChatListener = selectedChatStore.onChange('selectedChat', async (newChat) => {
            if (newChat?.id !== this.prevChatId) {
                this.active = this.firstTab;
                this.renderedTabs = new Set([this.firstTab]);
                this.chatId = newChat?.id || '';
                this.prevChatId = newChat?.id || null;
            }
            await this.initialize(newChat);
        });
        this.disposeProfilePanelListener = profilePanelStore.onChange('isSelectTab', (newValue) => {
            if (newValue === 'ticket') {
                this.active = 'ticket';
                profilePanelStore.set('isSelectTab', 'profile');
            }
        });
    }
    componentDidLoad() {
        this.scrollContainer?.addEventListener('scroll', this.checkScroll);
        this.resizeObserver = new ResizeObserver(() => this.checkScroll());
        if (this.scrollContainer) {
            this.resizeObserver.observe(this.scrollContainer);
        }
        this.checkScroll();
    }
    componentDidRender() {
        if (this.scrollContainer && this.resizeObserver) {
            this.resizeObserver.observe(this.scrollContainer);
        }
        this.checkScroll();
        if (this.active !== this.lastActive) {
            this.scrollToActiveTab();
            this.lastActive = this.active;
        }
    }
    disconnectedCallback() {
        if (this.disposeSelectedChatListener)
            this.disposeSelectedChatListener();
        if (this.disposeProfilePanelListener)
            this.disposeProfilePanelListener();
        this.scrollContainer?.removeEventListener('scroll', this.checkScroll);
        this.resizeObserver?.disconnect();
    }
    watchActive(newValue) {
        if (!this.renderedTabs.has(newValue)) {
            this.renderedTabs = new Set([...this.renderedTabs, newValue]);
        }
    }
    get isShowZrmz() {
        const zwizPackageData = getZwizPackageData();
        return !!zwizPackageData?.zrmz?.business_id;
    }
    get isShowZerva() {
        const zwizPackageData = getZwizPackageData();
        return !!zwizPackageData?.zerva?.business_id;
    }
    tabs() {
        const t = useTranslation();
        const selectedChat = selectedChatStore.get('selectedChat');
        const _connection = configStore.get('connectionList').find(connection => connection.type === 'zwiz' && connection.channels?.find(channel => channel.id === selectedChat?.connection?.id));
        const tabs = [
            {
                label: t('info'),
                value: 'info',
            },
        ];
        if (_connection && _connection?.type === 'zwiz') {
            if (_connection?.platform === 'sme' && selectedChat.type === 'user') {
                tabs.push({
                    label: t('order_summary'),
                    value: 'order',
                }, {
                    label: t('cart_summary'),
                    value: 'cart',
                });
            }
            if (_connection?.platform === 'enterprise') {
                tabs.push({
                    label: t('ticket'),
                    value: 'ticket',
                });
            }
        }
        if (this.isShowZrmz && selectedChat.type === 'user') {
            tabs.push({
                label: 'ZRMZ',
                value: 'zrmz',
            });
        }
        if (this.isShowZerva && selectedChat.type === 'user') {
            tabs.push({
                label: 'ZERVA',
                value: 'zerva',
            });
        }
        tabs.push({
            label: t('file_and_image'),
            value: 'media',
        });
        tabs.push({
            label: t('history'),
            value: 'history',
        });
        return tabs;
    }
    async initialize(chat) {
        const connectionItem = getConnectionItem(chat);
        if (connectionItem && connectionItem?.type === 'zwiz') {
            const connectionId = getConnectionId(connectionItem);
            if (connectionItem?.platform === 'sme' && !connectionItem.zwiz_package_data) {
                try {
                    this.isLoading = true;
                    const botResponse = await getZwizCheckBotPage(connectionId);
                    const connectionList = configStore.get('connectionList');
                    const updatedConnectionList = connectionList.map(connection => connection.id === connectionId ? { ...connection, ...getZwizPackageType(botResponse) } : connection);
                    configStore.set('connectionList', updatedConnectionList);
                }
                catch (error) {
                    handleError(error, "Failed to initialize SME");
                }
                finally {
                    this.isLoading = false;
                }
            }
            if (connectionItem?.platform === 'enterprise') {
                try {
                    this.isLoading = true;
                    const userToken = await getUserToken({ connectionId });
                    const userProfile = await getProfile({
                        connectionId,
                        token: userToken?.access_token
                    });
                    const zdeskBusinessId = connectionItem.type === 'zwiz' ? connectionItem.bot_id : '';
                    const businessUser = userProfile.data?.business_users.find(user => user.business_id === zdeskBusinessId);
                    const businessRequest = {
                        connectionId,
                        token: userToken?.access_token,
                        data: {
                            business_id: businessUser.business_id,
                            limit: 50
                        }
                    };
                    const [businessUsers, businessGroups, ticketStatusSettingsRes] = await Promise.all([
                        getBusinessUsers(businessRequest),
                        getBusinessGroups(businessRequest),
                        getTicketStatusSetting({ connectionId, token: userToken?.access_token }, { business_id: businessUser.business_id }),
                    ]);
                    userInfosStore.set(connectionId, {
                        token: userToken,
                        userProfile: userProfile.data
                    });
                    businessStore.set('users', businessUsers.data.data);
                    businessStore.set('groups', businessGroups.data.data);
                    businessStore.set('ticketStatusSettings', ticketStatusSettingsRes?.data ?? []);
                }
                catch (error) {
                    handleError(error, "Failed to initialize enterprise");
                }
                finally {
                    this.isLoading = false;
                }
            }
        }
        this.validateActiveTab();
    }
    validateActiveTab() {
        const tabs = this.tabs();
        const tabValues = tabs.map(tab => tab.value);
        if (!tabValues.includes(this.active)) {
            this.active = tabs[0]?.value || 'info';
        }
    }
    shouldRenderTab(tabName) {
        return this.renderedTabs.has(tabName);
    }
    isTabActive(tabName) {
        return this.active === tabName;
    }
    handleBackToMessages = () => {
        profilePanelStore.reset();
    };
    checkScroll = () => {
        if (this.scrollContainer) {
            const { scrollLeft, scrollWidth, clientWidth } = this.scrollContainer;
            this.canScrollLeft = scrollLeft > 0;
            this.canScrollRight = scrollLeft < scrollWidth - clientWidth - 1;
        }
    };
    scrollToActiveTab = () => {
        if (this.scrollContainer) {
            const activeTab = this.scrollContainer.querySelector('[aria-selected="true"]');
            if (activeTab) {
                activeTab.scrollIntoView({
                    behavior: 'smooth',
                    block: 'nearest',
                    inline: 'center',
                });
            }
        }
    };
    scroll = (direction) => {
        if (this.scrollContainer) {
            const offset = this.scrollContainer.clientWidth * 0.75;
            this.scrollContainer.scrollBy({
                left: direction === 'left' ? -offset : offset,
                behavior: 'smooth',
            });
        }
    };
    render() {
        const isZwiz = configStore.get('isZwiz');
        const isShowWarning = String(configStore.get('isShowWarningNotification')) === 'true';
        return (h(Host, { key: '823e332b3eb6a1c765daf562d0ef43bf2adbfff4' }, h("div", { key: '67be248caae05f5792cc2598241d3e394ad06d85', class: `profile-tabs ${isZwiz ? 'z-zwiz-max-height' : 'z-max-height'} ${isShowWarning ? 'has-warning-notification' : ''}` }, this.isLoading
            ? h("div", { class: "flex items-center justify-center h-full" }, h(Icon, { name: "LoaderCircle", addClass: "mx-auto size-5 animate-spin text-gray-400" }))
            : h(Fragment, null, h("div", { class: "profile-tabs-wrapper" }, h("div", { class: "profile-tabs-list-wrapper" }, deviceModeStore.get('mode') !== 'desktop' && (h("div", { class: "profile-tabs-back-button-wrapper" }, h(ZIconButton, { variant: "none", iconName: "ChevronLeft", onClick: this.handleBackToMessages }))), h("div", { class: "relative flex-1 overflow-hidden" }, deviceModeStore.get('mode') === 'desktop' && this.canScrollLeft && (h("div", { class: "profile-tabs-scroll-button left-0 bg-gradient-to-r from-background via-background to-transparent" }, h(ZIconButton, { variant: "none", iconName: "ChevronLeft", onClick: () => this.scroll('left') }))), h("ul", { role: "tablist", class: `profile-tabs-list scroll-container ${deviceModeStore.get('mode') === 'desktop' ? 'no-scrollbar' : ''}`, ref: el => (this.scrollContainer = el) }, this.tabs().map(({ label, value }) => (h("li", { role: "presentation" }, h("button", { role: "tab", "data-value": value, onClick: () => (this.active = value), class: 'profile-tabs-item ' +
                    (this.active === value ? 'text-primary font-medium border-primary' : 'text-surface border-transparent filter hover:brightness-110'), "aria-selected": this.active === value ? 'true' : 'false' }, label))))), deviceModeStore.get('mode') === 'desktop' && this.canScrollRight && (h("div", { class: "profile-tabs-scroll-button right-0 bg-gradient-to-l from-background via-background to-transparent" }, h(ZIconButton, { variant: "none", iconName: "ChevronRight", onClick: () => this.scroll('right') })))))), h("div", { id: "profile-tabs-content", class: "profile-tabs-content scroll-container", key: this.chatId }, this.shouldRenderTab('info') && (h("div", { class: this.isTabActive('info') ? 'h-full' : 'hidden' }, h("profile-info", null))), this.shouldRenderTab('media') && (h("div", { class: this.isTabActive('media') ? 'h-full' : 'hidden' }, h("profile-media", null))), this.shouldRenderTab('order') && (h("div", { class: this.isTabActive('order') ? 'h-full' : 'hidden' }, h("profile-order-summary", null))), this.shouldRenderTab('cart') && (h("div", { class: this.isTabActive('cart') ? 'h-full' : 'hidden' }, h("profile-cart-summary", null))), this.shouldRenderTab('ticket') && (h("div", { class: this.isTabActive('ticket') ? 'h-full' : 'hidden' }, h("profile-ticket", null))), this.shouldRenderTab('zrmz') && (h("div", { class: this.isTabActive('zrmz') ? 'h-full' : 'hidden' }, h("profile-zrmz", null))), this.shouldRenderTab('zerva') && (h("div", { class: this.isTabActive('zerva') ? 'h-full' : 'hidden' }, h("profile-zerva", null))), this.shouldRenderTab('history') && (h("div", { class: this.isTabActive('history') ? 'h-full' : 'hidden' }, h("profile-history", null))))))));
    }
    static get is() { return "profile-tabs"; }
    static get originalStyleUrls() {
        return {
            "$": ["profile-tabs.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["profile-tabs.css"]
        };
    }
    static get states() {
        return {
            "active": {},
            "renderedTabs": {},
            "chatId": {},
            "isLoading": {},
            "canScrollLeft": {},
            "canScrollRight": {}
        };
    }
    static get watchers() {
        return [{
                "propName": "active",
                "methodName": "watchActive"
            }];
    }
}
