import { Host, h } from "@stencil/core";
import { configStore, storageUsageStore } from "../../store/store";
import { setupLanguage, setupTheme, setupBusinessId, setupShopId, setupAccessToken, setupIsProduction, setupTimeZone, setupPackage } from "../../utils/setup";
import { useTranslation } from "../../utils/utils";
import { getQuickMessageLibraryFilesStorageUsage } from "../../api/quick-message";
import { handleError } from "../../store/dialog";
import { convertBytesToGB } from "../../utils/func";
export class QuickMessageAppComponent {
    languagePref = 'en';
    themeMode = 'light';
    templateData;
    imageLibrary;
    fileLibrary;
    businessId;
    shopId;
    accessToken;
    isProduction;
    timeZone;
    currentPackage;
    activeTab = 'template';
    templates = [];
    images = [];
    files = [];
    templatesChange;
    imagesChange;
    filesChange;
    tabs = [
        { id: 'template', labelKey: 'quick_message.tab_template' },
        { id: 'image', labelKey: 'image' },
        { id: 'file', labelKey: 'file' },
    ];
    connectedCallback() {
        setupLanguage(this.languagePref);
        setupTheme(this.themeMode);
        setupBusinessId(this.businessId);
        setupShopId(this.shopId);
        setupAccessToken(this.accessToken);
        setupIsProduction(this.isProduction);
        setupTimeZone(this.timeZone);
        setupPackage(this.currentPackage);
    }
    async componentWillLoad() {
        this.templates = this.parseTemplates(this.templateData);
        this.images = this.parseLibrary(this.imageLibrary);
        this.files = this.parseLibrary(this.fileLibrary);
        setupBusinessId(this.businessId);
        setupShopId(this.shopId);
        setupAccessToken(this.accessToken);
        setupIsProduction(this.isProduction);
        setupTimeZone(this.timeZone);
        setupPackage(this.currentPackage);
        await this.loadUsageStorage();
    }
    handleLanguageChange(newLang) {
        setupLanguage(newLang);
    }
    handleThemeChange(newTheme) {
        setupTheme(newTheme);
    }
    handleTemplateDataChange(newValue) {
        this.templates = this.parseTemplates(newValue);
    }
    handleImageLibraryChange(newValue) {
        this.images = this.parseLibrary(newValue);
    }
    handleFileLibraryChange(newValue) {
        this.files = this.parseLibrary(newValue);
    }
    handleBusinessIdChange(newValue) {
        setupBusinessId(newValue);
    }
    handleShopIdChange(newValue) {
        setupShopId(newValue);
    }
    handleAccessTokenChange(newValue) {
        setupAccessToken(newValue);
    }
    handleIsProductionChange(newValue) {
        setupIsProduction(newValue);
    }
    handleTimeZoneChange(newValue) {
        setupTimeZone(newValue);
    }
    handleCurrentPackageChange(newValue) {
        setupPackage(newValue);
    }
    deserializeCurrentPackage(value) {
        try {
            return JSON.parse(value);
        }
        catch (e) {
            return null;
        }
    }
    parseTemplates(value) {
        if (!value) {
            return [];
        }
        if (typeof value === 'string') {
            try {
                const parsed = JSON.parse(value);
                return this.cloneTemplates(parsed);
            }
            catch (error) {
                console.warn('[quick-message-app] Failed to parse template data', error);
                return [];
            }
        }
        return this.cloneTemplates(value);
    }
    parseLibrary(value) {
        if (!value) {
            return [];
        }
        if (typeof value === 'string') {
            try {
                const parsed = JSON.parse(value);
                return this.cloneLibrary(parsed);
            }
            catch (error) {
                console.warn('[quick-message-app] Failed to parse library data', error);
                return [];
            }
        }
        return this.cloneLibrary(value);
    }
    cloneTemplates(templates) {
        return (templates || []).map(template => {
            const rawContents = template.contents || [];
            const normalizedContents = rawContents.map(content => {
                const rawMenuList = content.menu_list || [];
                const menuList = rawMenuList.map(menu => ({
                    ...menu,
                    buttons: (menu.buttons || []).map(button => ({ ...button })),
                }));
                return {
                    ...content,
                    buttons: (content.buttons || []).map(button => ({ ...button })),
                    menu_list: menuList,
                    menuList,
                };
            });
            return {
                ...template,
                content: normalizedContents,
            };
        });
    }
    cloneLibrary(library) {
        return (library || []).map(item => ({
            ...item,
            isSelected: item.isSelected || false,
        }));
    }
    handleTemplatesChange(event) {
        const next = this.cloneTemplates(event.detail || []);
        this.templates = next;
        this.templatesChange.emit(next);
    }
    handleImagesChange(event) {
        const next = this.cloneLibrary(event.detail || []);
        this.images = next;
        this.imagesChange.emit(next);
    }
    handleFilesChange(event) {
        const next = this.cloneLibrary(event.detail || []);
        this.files = next;
        this.filesChange.emit(next);
    }
    setActiveTab = (tab) => {
        this.activeTab = tab;
    };
    handleTabClick = (tab) => () => {
        this.setActiveTab(tab);
    };
    onTemplatesChange = (event) => {
        this.handleTemplatesChange(event);
    };
    onImagesChange = (event) => {
        this.handleImagesChange(event);
    };
    onFilesChange = (event) => {
        this.handleFilesChange(event);
    };
    async loadUsageStorage() {
        try {
            const usage = await getQuickMessageLibraryFilesStorageUsage();
            storageUsageStore.set('usage', convertBytesToGB(usage.total_storage_bytes));
        }
        catch (error) {
            handleError(error, 'Failed to load usage storage');
        }
    }
    render() {
        const t = useTranslation();
        const theme = configStore.get('theme');
        return (h(Host, { key: 'fbfb548e4907128c5056b6de03ecc5c0af5fdb7e', class: "quick-message-app__host bg-background text-surface", "data-theme": theme }, h("div", { key: 'b43f652dd805e022dc9041137f0cbcc14c6ac7af', class: "quick-message-app__shell px-4" }, h("header", { key: 'eb57f9f8b36f7455d4ebf804f122d2c4b5ed106e', class: "quick-message-app__header" }, h("div", { key: 'f06cb8fa5d0968e5034eccb0a1560853504f6b54', class: "quick-message-app__header-text" }, h("h1", { key: 'ffd987c64c1106dcddf7abf83c54da9d8e82cf84' }, t('quick_message.title')))), h("nav", { key: '198f0b2a1120255c0c81551a40a138cae2b51231', class: "quick-message-app__tabs text-sm" }, this.tabs.map(tab => (h("button", { key: tab.id, type: "button", class: this.activeTab === tab.id ? 'active' : '', onClick: this.handleTabClick(tab.id) }, t(tab.labelKey))))), h("section", { key: 'ef650b4b1f355514cf6a17545940f3bfa21ea6ba', class: "quick-message-app__content" }, this.activeTab === 'template' && h("quick-message-template", { key: 'f4c4853d42e52ad3ecd51e9235b273823bfb36d8', value: this.templates, onTemplatesChange: this.onTemplatesChange, isMaster: true }), this.activeTab === 'image' && h("quick-message-image", { key: '490da392076bc34d2f832022dc55bc245509c882', value: this.images, onImagesChange: this.onImagesChange, isMaster: true }), this.activeTab === 'file' && h("quick-message-file", { key: '73b2728dcb2afa9db61ea1f46e02266f1d426be6', value: this.files, onFilesChange: this.onFilesChange, isMaster: true }))), h("z-dialog", { key: 'ee7862048c931619c76a5de422b2b6a1a8e5c7e8' })));
    }
    static get is() { return "quick-message-app"; }
    static get originalStyleUrls() {
        return {
            "$": ["quick-message-app.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["quick-message-app.css"]
        };
    }
    static get deserializers() {
        return [{
                "propName": "currentPackage",
                "methodName": "deserializeCurrentPackage"
            }];
    }
    static get properties() {
        return {
            "languagePref": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'th' | 'en'",
                    "resolved": "\"en\" | \"th\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "language-pref",
                "defaultValue": "'en'"
            },
            "themeMode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'dark' | 'light'",
                    "resolved": "\"dark\" | \"light\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "theme-mode",
                "defaultValue": "'light'"
            },
            "templateData": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | QuickMessageTemplateModel[]",
                    "resolved": "QuickMessageTemplate[] | string",
                    "references": {
                        "QuickMessageTemplateModel": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplate",
                            "referenceLocation": "QuickMessageTemplate"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "template-data"
            },
            "imageLibrary": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | QuickMessageLibraryFile[]",
                    "resolved": "QuickMessageLibraryFile[] | string",
                    "references": {
                        "QuickMessageLibraryFile": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageLibraryFile",
                            "referenceLocation": "QuickMessageLibraryFile"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "image-library"
            },
            "fileLibrary": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | QuickMessageLibraryFile[]",
                    "resolved": "QuickMessageLibraryFile[] | string",
                    "references": {
                        "QuickMessageLibraryFile": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageLibraryFile",
                            "referenceLocation": "QuickMessageLibraryFile"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "file-library"
            },
            "businessId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "business-id"
            },
            "shopId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "shop-id"
            },
            "accessToken": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "access-token"
            },
            "isProduction": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "string | boolean",
                    "resolved": "boolean | string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-production"
            },
            "timeZone": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "time-zone"
            },
            "currentPackage": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "TPackageConfig",
                    "resolved": "{ name?: EnumPackage; level?: number; remainingDays?: number; maxChannel: number; maxAdmin?: number; maxStorage: number; maxTemplateMessage: number; maxChatHistory: number; }",
                    "references": {
                        "TPackageConfig": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::TPackageConfig",
                            "referenceLocation": "TPackageConfig"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "attribute": "current-package"
            }
        };
    }
    static get states() {
        return {
            "activeTab": {},
            "templates": {},
            "images": {},
            "files": {}
        };
    }
    static get events() {
        return [{
                "method": "templatesChange",
                "name": "templatesChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "QuickMessageTemplateModel[]",
                    "resolved": "QuickMessageTemplate[]",
                    "references": {
                        "QuickMessageTemplateModel": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplate",
                            "referenceLocation": "QuickMessageTemplate"
                        }
                    }
                }
            }, {
                "method": "imagesChange",
                "name": "imagesChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "QuickMessageLibraryFile[]",
                    "resolved": "QuickMessageLibraryFile[]",
                    "references": {
                        "QuickMessageLibraryFile": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageLibraryFile",
                            "referenceLocation": "QuickMessageLibraryFile"
                        }
                    }
                }
            }, {
                "method": "filesChange",
                "name": "filesChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "QuickMessageLibraryFile[]",
                    "resolved": "QuickMessageLibraryFile[]",
                    "references": {
                        "QuickMessageLibraryFile": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageLibraryFile",
                            "referenceLocation": "QuickMessageLibraryFile"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "languagePref",
                "methodName": "handleLanguageChange"
            }, {
                "propName": "themeMode",
                "methodName": "handleThemeChange"
            }, {
                "propName": "templateData",
                "methodName": "handleTemplateDataChange"
            }, {
                "propName": "imageLibrary",
                "methodName": "handleImageLibraryChange"
            }, {
                "propName": "fileLibrary",
                "methodName": "handleFileLibraryChange"
            }, {
                "propName": "businessId",
                "methodName": "handleBusinessIdChange"
            }, {
                "propName": "shopId",
                "methodName": "handleShopIdChange"
            }, {
                "propName": "accessToken",
                "methodName": "handleAccessTokenChange"
            }, {
                "propName": "isProduction",
                "methodName": "handleIsProductionChange"
            }, {
                "propName": "timeZone",
                "methodName": "handleTimeZoneChange"
            }, {
                "propName": "currentPackage",
                "methodName": "handleCurrentPackageChange"
            }];
    }
}
