import { Host, h } from "@stencil/core";
import { getChatFiles } from "../../api";
import { configStore, selectedChatStore } from "../../store/store";
import { useTranslation } from "../../utils/utils";
import { handleError } from "../../store/dialog";
import { Icon } from "../internal-component/icon";
import { downloadFileMessage, getFileTypeFromMime, openWindow } from "../../utils/func";
import { displayDate } from "../../utils/dayjs";
import { ZButton } from "../internal-component/z-button";
import { MediaSkeleton } from "../internal-component/media-skeleton";
import { BASE_ZIGNAL_CMS_URL } from "../../utils/constant";
export class ProfileMedia {
    disposeListener;
    isLoading = false;
    files = [];
    activeTab = 'image';
    showDialog = { open: false };
    errorUrls = new Set();
    loadedUrls = new Set();
    prevSelectedChat = null;
    async componentWillLoad() {
        this.disposeListener = selectedChatStore.onChange('selectedChat', async (newChat) => {
            if (!newChat) {
                this.files = [];
                this.loadedUrls = new Set(); // Reset when chat changes
                return;
            }
            if (newChat.id !== (this.prevSelectedChat ? this.prevSelectedChat.id : '')) {
                this.loadedUrls = new Set(); // Reset when chat changes
                this.errorUrls = new Set(); // Reset when chat changes
                await this.loadFiles();
                this.prevSelectedChat = newChat;
            }
        });
        // Initial load if a chat is already selected
        if (selectedChatStore.get('selectedChat')) {
            await this.loadFiles();
        }
    }
    disconnectedCallback() {
        if (this.disposeListener)
            this.disposeListener();
    }
    handleError = (url) => {
        this.errorUrls = new Set([...this.errorUrls, url]);
    };
    handleLoad = (url) => {
        this.loadedUrls = new Set([...this.loadedUrls, url]);
    };
    async loadFiles() {
        const selectedChat = selectedChatStore.get('selectedChat');
        if (!selectedChat)
            return;
        try {
            this.isLoading = true;
            const res = await getChatFiles({ sessionId: selectedChat.id });
            this.files = res.files || [];
        }
        catch (error) {
            this.files = [];
            handleError(error, 'Failed to load files');
        }
        finally {
            this.isLoading = false;
        }
    }
    isMediaFile(file) {
        const mime = file.mime_type?.toLowerCase() || '';
        return mime.startsWith('image/') || mime.startsWith('video/');
    }
    isDocumentFile(file) {
        return !this.isMediaFile(file);
    }
    getFilteredFiles() {
        if (this.activeTab === 'image') {
            return this.files.filter(file => this.isMediaFile(file));
        }
        return this.files.filter(file => this.isDocumentFile(file));
    }
    handleTabChange = (tab) => {
        this.activeTab = tab;
    };
    getFileIcon(mimeType) {
        const fileType = getFileTypeFromMime(mimeType);
        switch (fileType.type) {
            case 'excel':
            case 'csv':
                return 'excel';
            case 'pdf':
                return 'pdf';
            case 'word':
                return 'word';
            case 'powerpoint':
                return 'powerpoint';
            default:
                return 'file';
        }
    }
    handleOpenDialog = ({ url, type }) => {
        this.showDialog = { open: true, url, type };
    };
    handleCloseDialog = () => {
        this.showDialog = { open: false };
    };
    handleDownloadFile = async (file) => {
        await downloadFileMessage(file);
    };
    renderTabButtons() {
        const t = useTranslation();
        return (h("div", { class: "profile-media-tabs" }, ['image', 'file'].map((tab) => {
            return (h(ZButton, { title: t(tab), label: t(tab), size: "small", variant: this.activeTab === tab ? 'primary' : 'outlined', onClick: () => this.handleTabChange(tab) }));
        })));
    }
    renderImageGrid() {
        const files = this.getFilteredFiles();
        const t = useTranslation();
        if (files.length === 0) {
            return (h("div", { class: "profile-media-empty" }, h("span", { class: "text-sm text-surface" }, t('quick_message.image_empty'))));
        }
        return (h("div", { class: "profile-media-grid" }, files.map(file => {
            const isVideo = file.mime_type?.startsWith('video/');
            return (h("div", { class: "profile-media-grid-item", onClick: () => this.handleOpenDialog({
                    url: file.url,
                    type: file.mime_type?.split('/')[0]
                }) }, !this.loadedUrls.has(file.url) && h(MediaSkeleton, null), isVideo ? (h("div", { class: "profile-media-video-wrapper" }, h("video", { src: file.url, preload: "metadata", class: "profile-media-thumbnail", onError: () => this.handleError(file.url), onLoadedData: () => this.handleLoad(file.url) }), h("div", { class: "profile-media-play-icon" }, h(Icon, { name: "Play", addClass: "size-6" })))) : (h("img", { src: file.url, alt: file.name || 'image', class: "profile-media-thumbnail", onError: () => this.handleError(file.url), onLoad: () => this.handleLoad(file.url), loading: "lazy" }))));
        })));
    }
    renderFileList() {
        const files = this.getFilteredFiles();
        const t = useTranslation();
        if (files.length === 0) {
            return (h("div", { class: "profile-media-empty" }, h("span", { class: "text-sm text-surface" }, t('quick_message.file_empty'))));
        }
        return (h("div", { class: "profile-media-file-list" }, files.map(file => {
            const iconName = this.getFileIcon(file.mime_type);
            const fileName = file.name || 'Unknown file';
            return (h("div", { class: "profile-media-file-item-wrapper", onClick: () => this.handleDownloadFile(file) }, h("div", { class: "profile-media-file-item" }, h("div", { class: "profile-media-file-icon" }, iconName !== 'file' ? (h("img", { src: `https://zwizai-platform.s3.ap-southeast-1.amazonaws.com/zignal-package/${iconName}.png`, alt: iconName, class: "size-8" })) : (h(Icon, { name: "File", addClass: "size-8" }))), h("div", { class: "profile-media-file-info" }, h("span", { class: "profile-media-file-name", title: fileName }, fileName)), file.url && (h("span", { class: "profile-media-file-date text-theme-gray" }, displayDate(file?.created_at || new Date()))))));
        })));
    }
    render() {
        const t = useTranslation();
        return (h(Host, { key: '428b1689bbc1e70eb8d91d1b57c8ffe3e197a6d7' }, h("div", { key: '572fa888eead8e1bc7b1924021f094a93dd01053', class: "profile-media" }, this.renderTabButtons(), h("span", { key: '327799823e45c6e309ff04247da212873bbf25a0', class: "px-3 pb-1 text-xs text-surface" }, t('history_max_day', { days: configStore.get('package').maxChatHistory })), this.isLoading && (h("div", { key: 'c4be7f7d9722fcd173f88b159f2a5f511746f16d', class: "profile-media-loading" }, h("span", { key: '89b50a84306ec056de17b0272a2c0c239152f39e', class: "text-sm text-theme-gray" }, "Loading..."))), !this.isLoading && (h("div", { key: '66de8cc6f17f0a163190c197f9bb87b07e1b0f37', class: "profile-media-content scroll-container" }, this.activeTab === 'image' ? this.renderImageGrid() : this.renderFileList())), this.showDialog.open && (h("div", { key: '7d28330259e47d2732f08928b4cc4f18529107ab', class: "dialog-backdrop" }, h("dialog-preview-media", { key: '2c1a31ee486ee951ad268f35a6782fefb9da1e32', dialogType: this.showDialog.type, url: this.showDialog.url || '', onClose: this.handleCloseDialog }))), configStore.get('package').maxChatHistory === 0 && (h("div", { key: '126d105225645d7fff149490f8430bb00016df47', class: "absolute inset-0 z-50 flex items-center justify-center bg-black/40" }, h("div", { key: '900281349c731a38db19a60252b9b5b72472a565', class: "profile-media-warning-drawer" }, h(Icon, { key: 'd61a4d6a55c64fbb9c446ab4d729267a9e5b60eb', name: "AlertCircle", addClass: "h-[120px] w-[120px] text-primary mt-8 mb-4" }), h("span", { key: 'c514c622a3f3a5a9caf81173040ef0072532d261', class: "p-3 text-center text-theme-gray mb-4" }, t('package_expire')), h(ZButton, { key: '4fef46ffe32656058ad9835def4c9b2629fe6f90', title: t('upgrade_package'), label: t('upgrade_package'), onClick: () => {
                const _baseUrl = BASE_ZIGNAL_CMS_URL();
                const baseUrl = `${_baseUrl}/${configStore.get('language')}/package`;
                if (configStore.get('isZwiz')) {
                    openWindow(`${baseUrl}?business_id=${configStore.get('businessId')}&shop_id=${configStore.get('shopId')}&access_token=${configStore.get('accessToken')}`);
                }
                else {
                    window.location.href = baseUrl;
                }
            } })))))));
    }
    static get is() { return "profile-media"; }
    static get originalStyleUrls() {
        return {
            "$": ["profile-media.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["profile-media.css"]
        };
    }
    static get states() {
        return {
            "isLoading": {},
            "files": {},
            "activeTab": {},
            "showDialog": {},
            "errorUrls": {},
            "loadedUrls": {}
        };
    }
}
