import { Host, h } from "@stencil/core";
import { getActivityLogs } from "../../api";
import { profilePanelStore, selectedChatStore } from "../../store/store";
import { handleGetChatMessages, scrollToMessage } from "../../store/message";
import { useTranslation } from "../../utils/utils";
import { displayDateTime } from "../../utils/dayjs";
import { ZTagOrStatusItem } from "../internal-component/z-tag-or-status-item";
import { handleError } from "../../store/dialog";
import { getSenderName } from "../../utils/func";
export class ProfileHistory {
    disposeListener;
    isLoading = false;
    logs = [];
    prevSelectedChat = null;
    async componentWillLoad() {
        this.disposeListener = selectedChatStore.onChange('selectedChat', async (newChat) => {
            if (!newChat) {
                this.logs = [];
                return;
            }
            if (newChat.id !== (this.prevSelectedChat ? this.prevSelectedChat.id : '')) {
                await this.loadLogs();
                this.prevSelectedChat = newChat;
            }
        });
        // Initial load if a chat is already selected
        if (selectedChatStore.get('selectedChat')) {
            await this.loadLogs();
        }
    }
    disconnectedCallback() {
        if (this.disposeListener)
            this.disposeListener();
    }
    async loadLogs() {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            return;
        try {
            this.isLoading = true;
            const { channel } = selectedChat;
            const type = selectedChat.type === 'group' ? 'group' : 'user';
            const selectedChatType = selectedChat[type];
            const id = selectedChatType ? selectedChatType.id : '';
            const res = await getActivityLogs({ type, channel, id });
            this.logs = res.activity_logs || [];
        }
        catch (error) {
            this.logs = [];
            handleError(error, 'Failed to load Activity Logs');
        }
        finally {
            this.isLoading = false;
        }
    }
    renderChip(item) {
        if (!item)
            return null;
        return (h(ZTagOrStatusItem, { item: {
                id: '',
                name: item.name,
                color: item.color,
                sequence: 0,
            } }));
    }
    getTypeText(log) {
        return (log.from ? log.from.type : '') || (log.to ? log.to.type : '') || (log.item ? log.item.type : '');
    }
    getActionText(log) {
        const t = useTranslation();
        const senderName = getSenderName(log.sender);
        return `${senderName} ${(() => {
            const action = log.action;
            const type = this.getTypeText(log);
            return t(`profile_tab.activity_action`)
                .replace('{action}', t(`${action}`))
                .replace('{type}', t(`${type}`))
                .toLowerCase();
        })()}`;
    }
    async handleGoToMessage(messageId) {
        try {
            profilePanelStore.reset();
            const isSuccessScroll = scrollToMessage({ messageId });
            if (!isSuccessScroll) {
                await handleGetChatMessages({ startMessageId: messageId });
                setTimeout(() => {
                    scrollToMessage({ messageId });
                }, 300);
            }
        }
        catch (error) {
            handleError(error, 'Failed to go to message');
        }
    }
    renderMenuList(logId) {
        const t = useTranslation();
        const menuItems = [
            {
                label: t('profile_tab.go_to_message'),
                value: 'go_to_message',
                onClick: () => this.handleGoToMessage(logId),
            },
        ];
        return h("menu-list", { menuItems: menuItems, referenceSelector: `log-${logId}`, iconName: "EllipsisVertical", noPaddingY: true });
    }
    renderActivityLog(log) {
        return (h("div", { class: "profile-history-box-activity-wrapper" }, h("div", { class: "profile-history-box-container" }, h("div", { class: `text-xs text-surface`, title: this.getActionText(log) }, log.created_at ? `${displayDateTime(log.created_at)} : ` : '', h("div", { class: "profile-history-box-action-text" }, h("div", { class: "truncate w-full" }, this.getActionText(log)), h("div", { class: "profile-history-box-wrapper" }, 'from' in log && log.from && this.renderChip(log.from), 'action' in log && log.action === 'change' && h("span", { class: `text-sm text-theme-gray` }, "\u2192"), 'to' in log && log.to && this.renderChip(log.to), 'item' in log && log.item && this.renderChip(log.item))))), h("div", { id: `log-${log.id}`, class: "profile-history-box-menu-list" }, this.renderMenuList(log.id))));
    }
    renderSummarizedChat(log) {
        const t = useTranslation();
        return (h("div", { class: "profile-history-box-wrapper" }, h("div", { class: "profile-history-box-container" }, h("div", { class: `profile-history-content-wrapper text-surface` }, log.created_at ? `${displayDateTime(log.created_at)} : ` : '', h("div", { class: `profile-history-box-container text-surface` }, h("typography-clamp", { text: `${t('chat_tab.summary')}\n${log.text}`, textColor: "z-text", lines: 3 })))), h("div", { id: `log-${log.id}`, class: "profile-history-box-menu-list" }, this.renderMenuList(log.id))));
    }
    render() {
        const t = useTranslation();
        return (h(Host, { key: 'e0f54442f40f9d7e6884534bc45330997145fc28' }, h("div", { key: '41fd2bcc5a14398d57f9d34b0e3cac5680de3296', class: "profile-history" }, h("div", { key: '734f7ba75731100d6182ebf5922026c16e348017', class: "profile-history-wrapper" }, t('profile_tab.history_info')), this.isLoading && (h("div", { key: '5d07e4f9ce547120ba8392134bdfde9e8db23b0e', class: "profile-history-loading" }, h("span", { key: 'fd0954d8270c76d850f0a94d85e3cce5243248b3', class: "text-sm text-theme-gray" }, "Loading..."))), !this.isLoading && this.logs.length === 0 && (h("div", { key: 'afb0cfbcffa886d5c42278c432d2c260d4467b6a', class: "profile-history-no-activity" }, h("span", { key: 'c182af42dbc90c77ef36b1be06243dcf33ddc4c0', class: "text-sm text-surface" }, t('profile_tab.no_activity_log')))), !this.isLoading && this.logs.length > 0 && (h("ul", { key: '1ea1bd6313ea8e385e1c3911cdc7cb8fbd5cc348', class: "profile-history-content" }, this.logs.map(log => (h("li", { class: "py-2" }, log.type === 'summarized_chat' ? this.renderSummarizedChat(log) : this.renderActivityLog(log)))))))));
    }
    static get is() { return "profile-history"; }
    static get originalStyleUrls() {
        return {
            "$": ["profile-history.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["profile-history.css"]
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "logs": {}
        };
    }
}
