import { Host, h } from "@stencil/core";
import { useTranslation } from "../../utils/utils";
import { Icon } from "../internal-component/icon";
import { t } from "i18next";
import { ZButton } from "../internal-component/z-button";
import dayjs from "dayjs";
export class QuickMessageAddTemplateComponent {
    handleClose;
    handleSave;
    handleSend;
    initialTemplate;
    mode = 'edit';
    isSaving = false;
    draftTemplate = this.createTemplateState();
    componentWillLoad() {
        this.draftTemplate = this.createTemplateState(this.initialTemplate);
    }
    handleInitialTemplateChange(newTemplate) {
        this.draftTemplate = this.createTemplateState(newTemplate);
    }
    createTemplateState(template) {
        if (!template) {
            return {
                id: 'template-' + Date.now(),
                title: '',
                last_updated_at: dayjs().toDate(),
                last_updated_by: 'zignal-bot',
                isExpanded: false,
                contents: [],
            };
        }
        return {
            ...template,
            contents: (template.contents || []).map(content => ({
                ...content,
                buttons: [...(content.buttons || [])],
                fileUrl: content.file_url,
                file: content.file,
                menuList: (content.menu_list || []).map(menu => ({
                    ...menu,
                    fileUrl: menu.file_url,
                    file: menu.file,
                    buttons: [...(menu.buttons || [])],
                })),
            })),
        };
    }
    templateOptions = [
        { icon: 'MessageSquareText', label: t('quick_message.message'), onClick: () => this.addTemplateContent('text') },
        { icon: 'Touchpad', label: t('quick_message.button'), onClick: () => this.addTemplateContent('button') },
        { icon: 'Image', label: t('image'), onClick: () => this.addTemplateContent('image') },
        { icon: 'SquareMenu', label: t('quick_message.menu_list'), onClick: () => this.addTemplateContent('menu_list') },
        { icon: 'Play', label: t('video'), onClick: () => this.addTemplateContent('video') },
    ];
    addTemplateContent(type) {
        if (this.isSaving) {
            return;
        }
        if (this.draftTemplate.contents.length >= 5) {
            return;
        }
        let menuList = [];
        if (type === 'menu_list') {
            menuList = [
                {
                    id: 'menu-' + Date.now(),
                    title: '',
                    description: '',
                    buttons: [],
                },
            ];
        }
        const newContent = {
            id: 'content-' + Date.now(),
            type,
            buttons: [],
            files: [],
            menu_list: menuList,
            text: '',
            translateText: '',
        };
        this.draftTemplate = { ...this.draftTemplate, contents: [...this.draftTemplate.contents, newContent] };
    }
    updateTemplateContent(content) {
        if (content.type === 'menu_list' && content.menu_list.length === 0) {
            this.draftTemplate = { ...this.draftTemplate, contents: this.draftTemplate.contents.filter(c => c.id !== content.id) };
            return;
        }
        this.draftTemplate = { ...this.draftTemplate, contents: this.draftTemplate.contents.map(c => (c.id === content.id ? content : c)) };
    }
    removeTemplateContent(contentId) {
        if (this.isSaving) {
            return;
        }
        this.draftTemplate = {
            ...this.draftTemplate,
            contents: this.draftTemplate.contents.filter(content => content.id !== contentId),
        };
    }
    reorderTemplateContent(contentId, direction) {
        if (this.isSaving) {
            return;
        }
        const currentIndex = this.draftTemplate.contents.findIndex(content => content.id === contentId);
        if (currentIndex === -1) {
            return;
        }
        const targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;
        if (targetIndex < 0 || targetIndex >= this.draftTemplate.contents.length) {
            return;
        }
        const updatedContent = [...this.draftTemplate.contents];
        [updatedContent[currentIndex], updatedContent[targetIndex]] = [updatedContent[targetIndex], updatedContent[currentIndex]];
        this.draftTemplate = {
            ...this.draftTemplate,
            contents: updatedContent,
        };
    }
    renderTemplateContent(content) {
        switch (content.type) {
            case 'text':
                return h("quick-message-text-content", { content: content, onContentChange: (event) => this.updateTemplateContent(event.detail) });
            case 'button':
                return h("quick-message-button-content", { content: content, onContentChange: (event) => this.updateTemplateContent(event.detail) });
            case 'image':
                return h("quick-message-image-content", { content: content, onContentChange: (event) => this.updateTemplateContent(event.detail) });
            case 'menu_list':
                return (h("quick-message-menu-list-content", { content: content, onContentChange: (event) => this.updateTemplateContent(event.detail) }));
            case 'video':
                return h("quick-message-video-content", { content: content, onContentChange: (event) => this.updateTemplateContent(event.detail) });
            default:
                return null;
        }
    }
    render() {
        const t = useTranslation();
        const isSendMode = this.mode === 'edit-send';
        const isCreateMode = this.mode === 'create';
        const isTitleEmpty = this.draftTemplate.title.trim() === '';
        return (h(Host, { key: 'b1df6fae5ba115d8f870d2b4ee1b0742fa913a11' }, h("div", { key: '48c6c6f8401005fd040a2b52e51a42e136bc3f71', class: "quick-message-add-template-overlay", onClick: () => this.handleClose() }, h("div", { key: 'de0f50a8c38d517f1762645c446571a4e0ca25d3', class: `quick-message-add-template-container bg-background text-surface px-6 py-4`, onClick: event => event.stopPropagation() }, h("div", { key: '59efede95a4657bda0ae8772320dbc260de9f3d3', class: "flex items-center justify-between" }, h("h2", { key: 'b6128d5e7315d228f76cba4816fe17d8da3764d0', class: "mb-4 text-lg font-semibold" }, isCreateMode ? t('quick_message.add_template') : t('quick_message.edit_template')), h("button", { key: 'b84ad3986d23171c19b3fa10c548ebee5e7fa49f', type: "button", onClick: () => this.handleClose(), class: "cursor-pointer" }, h(Icon, { key: '97b3562880b665591fb452904e4e7286df85444c', name: "X" }))), h("div", { key: 'd7ab302aad90f92f42498e9bb668280b41f0be32', class: `flex flex-col h-full gap-2 overflow-auto rounded-xl border-primary border-[1.5px] p-3` }, h("input", { key: '17f7efe71a4f93b18ffa3d667c54b0642c1d828b', type: "text", class: `w-full px-4 py-2 rounded-xl border-primary border-[1.5px] focus:outline-none ring-primary placeholder-surface text-surface bg-background`, placeholder: t('quick_message.template_name'), value: this.draftTemplate.title, onInput: e => {
                this.draftTemplate = { ...this.draftTemplate, title: e.target.value };
            } }), isTitleEmpty && h("p", { key: '33975156cd64d3345188bcdff28d328d2bef51f6', class: "pl-2 text-xs text-red-500" }, t('quick_message.template_name_warning')), h("span", { key: 'a9782036f6542aad7b87d0070fb9eb1d0cec4b09', class: "text-xs pl-2" }, t('quick_message.count_template_content'), " ", this.draftTemplate.contents.length, "/5"), h("div", { key: 'a7698811f571cc33f58ea94da3614356366f9faf' }, this.draftTemplate.contents.map((content, index) => {
            const isFirst = index === 0;
            const isLast = index === this.draftTemplate.contents.length - 1;
            return (h("div", { key: content.id, class: "mt-2 flex items-start gap-3" }, h("div", { class: "flex items-center gap-2" }, h("div", { class: "flex flex-col items-center gap-2" }, !isFirst && (h("button", { type: "button", class: `inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full border-[1.5px] border-primary text-primary transition-colors hover:bg-slate-100 focus:outline-none focus:ring-2 focus:ring-slate-200 ${this.isSaving ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`, "aria-label": t('quick_message.move_up'), disabled: this.isSaving, onClick: () => !this.isSaving && this.reorderTemplateContent(content.id, 'up') }, h(Icon, { name: "ChevronUp", addClass: "size-4" }))), !isLast && (h("button", { type: "button", class: `inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full border-[1.5px] border-primary text-primary transition-colors hover:bg-slate-100 focus:outline-none focus:ring-2 focus:ring-slate-200 ${this.isSaving ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`, "aria-label": t('quick_message.move_down'), disabled: this.isSaving, onClick: () => !this.isSaving && this.reorderTemplateContent(content.id, 'down') }, h(Icon, { name: "ChevronDown", addClass: "size-4" })))), h("button", { type: "button", class: `inline-flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-full border border-red-500 text-red-500 transition-colors hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-200 ${this.isSaving ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'}`, "aria-label": t('remove'), disabled: this.isSaving, onClick: () => !this.isSaving && this.removeTemplateContent(content.id) }, h(Icon, { name: "Trash2", addClass: "size-4" }))), h("div", { class: "flex-1 overflow-hidden" }, this.renderTemplateContent(content))));
        }))), h("div", { key: '1ba97093b0f3ce7b7bf50f2e8662babc3689c8de', class: `mt-2 flex rounded-xl border-[1.5px] border-primary` }, this.templateOptions.map((option, index) => (h("button", { type: "button", class: `flex flex-1 ${this.isSaving ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'} flex-col items-center justify-center gap-1 px-4 py-2 text-xs font-medium text-center focus:outline-none ${index === 0 ? '' : `border-l border-primary`} text-primary`, disabled: this.isSaving, onClick: () => !this.isSaving && option.onClick() }, h(Icon, { name: option.icon, addClass: `size-4 text-primary` }), h("span", { class: "max-sm:hidden" }, option.label))))), h("div", { key: '5aa7072f6718e82fe20c04ddbf38d11820f83857', class: "mt-2 grid w-full grid-cols-2 gap-2" }, h(ZButton, { key: '7704663507a7c94e1e33c3efa70fa4bf5788c99d', variant: "outlined", label: t('cancel'), fullWidth: true, disabled: this.isSaving, onClick: () => this.handleClose() }), isSendMode ? (h(ZButton, { variant: "primary", label: t('send'), fullWidth: true, onClick: () => this.handleSend({ ...this.draftTemplate, last_updated_at: dayjs().toDate() }), disabled: isTitleEmpty || this.isSaving, startIcon: this.isSaving ? h(Icon, { name: "Loader2", addClass: "size-4 animate-spin" }) : undefined })) : (h(ZButton, { variant: "primary", label: t('save'), fullWidth: true, onClick: () => this.handleSave({ ...this.draftTemplate, last_updated_at: dayjs().toDate() }), disabled: isTitleEmpty || this.isSaving, startIcon: this.isSaving ? h(Icon, { name: "Loader2", addClass: "size-4 animate-spin" }) : undefined })))))));
    }
    static get is() { return "quick-message-add-template"; }
    static get originalStyleUrls() {
        return {
            "$": ["quick-message-add-template.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["quick-message-add-template.css"]
        };
    }
    static get properties() {
        return {
            "handleClose": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "() => void",
                    "resolved": "() => void",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "handleSave": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(template: QuickMessageTemplateModel) => void",
                    "resolved": "(template: QuickMessageTemplate) => void",
                    "references": {
                        "QuickMessageTemplateModel": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplate",
                            "referenceLocation": "QuickMessageTemplate"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "handleSend": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(template: QuickMessageTemplateModel) => void",
                    "resolved": "(template: QuickMessageTemplate) => void",
                    "references": {
                        "QuickMessageTemplateModel": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplate",
                            "referenceLocation": "QuickMessageTemplate"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "initialTemplate": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "QuickMessageTemplateModel",
                    "resolved": "{ id: string; title: string; contents: QuickMessageTemplateContent[]; created_at?: string | Date; created_by?: string; last_updated_at: string | Date; last_updated_by: string; isExpanded?: boolean; }",
                    "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
            },
            "mode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "TemplateSelectionMode",
                    "resolved": "\"create\" | \"edit\" | \"edit-send\" | \"send\"",
                    "references": {
                        "TemplateSelectionMode": {
                            "location": "import",
                            "path": "../quick-message-modal/template-selection",
                            "id": "src/components/quick-message-modal/template-selection.ts::TemplateSelectionMode",
                            "referenceLocation": "TemplateSelectionMode"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "mode",
                "defaultValue": "'edit'"
            },
            "isSaving": {
                "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-saving",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "draftTemplate": {}
        };
    }
    static get watchers() {
        return [{
                "propName": "initialTemplate",
                "methodName": "handleInitialTemplateChange"
            }];
    }
}
