import { Fragment, h } from "@stencil/core";
import { configStore } from "../../store/store";
import { useTranslation } from "../../utils/utils";
import { Icon } from "../internal-component/icon";
import { MediaSkeleton } from "../internal-component/media-skeleton";
import { QuickMessageTemplateButtonList } from "./quick-message-template-button-list";
import { QuickMessageTemplateButtonDialog } from "./quick-message-template-button-dialog";
import { MAX_FILE_SIZE } from "../../utils/constant";
export class QuickMessageMenuListContentComponent {
    content;
    maxMenuList = 10;
    maxTitleLength = 80;
    maxDescriptionLength = 80;
    maxButtonCount = 3;
    maxButtonNameLength = 20;
    contentChange;
    isButtonDialogOpen = false;
    buttonDialogMenuId;
    buttonDialogLabel = '';
    buttonDialogAction = '';
    buttonDialogType = 'text';
    editingButtonId;
    menuErrors = {};
    loadedUrls = new Set();
    errorUrls = new Set();
    fileInputs = {};
    emitContent(update) {
        if (!this.content) {
            return;
        }
        const nextContent = { ...this.content, ...update };
        this.contentChange.emit(nextContent);
    }
    updateMenuList(updater) {
        if (!this.content) {
            return;
        }
        const currentMenus = this.content.menu_list || [];
        const nextMenus = updater(currentMenus);
        this.emitContent({ menu_list: nextMenus });
    }
    updateMenu(menuId, updater) {
        this.updateMenuList(menus => menus.map(menu => {
            if (menu.id !== menuId) {
                return menu;
            }
            const draft = {
                ...menu,
                buttons: [...(menu.buttons || [])],
            };
            return updater(draft);
        }));
    }
    handleImageLoad = (url) => {
        this.loadedUrls = new Set([...this.loadedUrls, url]);
    };
    handleImageError = (url) => {
        this.errorUrls = new Set([...this.errorUrls, url]);
    };
    handleAddMenu = () => {
        const totalMenus = this.content ? (this.content.menu_list || []).length : 0;
        if (totalMenus >= this.maxMenuList) {
            return;
        }
        const newMenu = {
            id: `menu-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
            title: '',
            description: '',
            buttons: [],
        };
        this.updateMenuList(menus => [...menus, newMenu]);
    };
    handleDeleteMenu(menuId) {
        this.updateMenuList(menus => menus.filter(menu => menu.id !== menuId));
        const { [menuId]: _, ...rest } = this.menuErrors;
        this.menuErrors = rest;
    }
    reorderMenu(menuId, direction) {
        this.updateMenuList(menus => {
            const currentIndex = menus.findIndex(menu => menu.id === menuId);
            if (currentIndex === -1) {
                return menus;
            }
            const targetIndex = direction === 'prev' ? currentIndex - 1 : currentIndex + 1;
            if (targetIndex < 0 || targetIndex >= menus.length) {
                return menus;
            }
            const nextMenus = [...menus];
            [nextMenus[currentIndex], nextMenus[targetIndex]] = [nextMenus[targetIndex], nextMenus[currentIndex]];
            return nextMenus;
        });
    }
    setMenuTitle(menuId, title) {
        this.updateMenu(menuId, menu => ({ ...menu, title }));
    }
    setMenuDescription(menuId, description) {
        this.updateMenu(menuId, menu => ({ ...menu, description }));
    }
    handleSelectImage(menuId) {
        if (this.fileInputs[menuId])
            this.fileInputs[menuId].click();
    }
    handleImageChange(menuId, event) {
        const input = event.target;
        if (!input.files) {
            return;
        }
        const file = input.files[0];
        const t = useTranslation();
        if (!file) {
            return;
        }
        if (file.size > MAX_FILE_SIZE) {
            this.menuErrors = { ...this.menuErrors, [menuId]: t('quick_message.image_too_large') };
            input.value = '';
            return;
        }
        const reader = new FileReader();
        reader.onload = () => {
            const url = reader.result;
            this.updateMenu(menuId, menu => ({ ...menu, file_url: url }));
            this.menuErrors = { ...this.menuErrors, [menuId]: undefined };
            input.value = '';
        };
        reader.readAsDataURL(file);
    }
    handleRemoveImage(menuId) {
        this.updateMenu(menuId, menu => ({ ...menu, file_url: undefined, file: undefined, file_id: undefined }));
        this.menuErrors = { ...this.menuErrors, [menuId]: undefined };
    }
    openButtonDialog(menuId, button) {
        this.buttonDialogMenuId = menuId;
        this.editingButtonId = button ? button.id : undefined;
        this.buttonDialogLabel = button ? button.text || '' : '';
        this.buttonDialogType = button ? button.action_type || 'text' : 'text';
        this.buttonDialogAction = button ? button.action || '' : '';
        this.isButtonDialogOpen = true;
    }
    closeButtonDialog() {
        this.isButtonDialogOpen = false;
        this.buttonDialogMenuId = undefined;
        this.editingButtonId = undefined;
        this.buttonDialogLabel = '';
        this.buttonDialogAction = '';
        this.buttonDialogType = 'text';
    }
    setButtonDialogType(type) {
        this.buttonDialogType = type;
        if (type === 'text') {
            this.buttonDialogAction = '';
        }
    }
    handleButtonSave() {
        if (!this.buttonDialogMenuId) {
            return;
        }
        const label = this.buttonDialogLabel.trim();
        const actionType = this.buttonDialogType;
        const actionValue = actionType === 'text' ? undefined : this.buttonDialogAction.trim();
        if (!label || (actionType !== 'text' && !actionValue)) {
            return;
        }
        const button = {
            id: this.editingButtonId || `menu-button-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
            action_type: actionType,
            text: label,
            action: actionValue,
        };
        this.updateMenu(this.buttonDialogMenuId, menu => {
            const buttons = menu.buttons || [];
            if (this.editingButtonId) {
                return {
                    ...menu,
                    buttons: buttons.map(current => (current.id === this.editingButtonId ? button : current)),
                };
            }
            if (buttons.length >= this.maxButtonCount) {
                return menu;
            }
            return { ...menu, buttons: [...buttons, button] };
        });
        this.closeButtonDialog();
    }
    handleDeleteButton() {
        if (!this.buttonDialogMenuId || !this.editingButtonId) {
            return;
        }
        this.updateMenu(this.buttonDialogMenuId, menu => ({
            ...menu,
            buttons: (menu.buttons || []).filter(button => button.id !== this.editingButtonId),
        }));
        this.closeButtonDialog();
    }
    reorderMenuButton(menuId, buttonId, direction) {
        this.updateMenu(menuId, menu => {
            const buttons = menu.buttons || [];
            const currentIndex = buttons.findIndex(button => button.id === buttonId);
            if (currentIndex === -1) {
                return menu;
            }
            const targetIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;
            if (targetIndex < 0 || targetIndex >= buttons.length) {
                return menu;
            }
            const nextButtons = [...buttons];
            [nextButtons[currentIndex], nextButtons[targetIndex]] = [nextButtons[targetIndex], nextButtons[currentIndex]];
            return { ...menu, buttons: nextButtons };
        });
    }
    renderMenuCard(menu, index, total, theme, t) {
        const title = menu.title || '';
        const description = menu.description || '';
        const buttons = menu.buttons || [];
        const error = this.menuErrors[menu.id];
        const isFirst = index === 0;
        const isLast = index === total - 1;
        return (h("div", { class: "relative flex shrink-0 flex-col", key: menu.id, "data-theme": theme }, h("div", { class: "relative flex w-[250px] flex-col overflow-hidden rounded-[18px] border-[1.5px] shadow-sm border-primary bg-background" }, h("div", { class: "pointer-events-none absolute left-3 right-3 top-3 z-10 flex items-center justify-between" }, h("div", { class: "flex items-center gap-2 pointer-events-auto" }, !isFirst && (h("button", { type: "button", class: "inline-flex h-8 w-8 items-center justify-center rounded-full border-[1.5px] border-primary text-primary bg-background transition-colors hover:bg-white focus:outline-none focus:ring-2 focus:ring-slate-200 cursor-pointer", "aria-label": t('quick_message.move_left'), onClick: () => this.reorderMenu(menu.id, 'prev') }, h(Icon, { name: "ChevronLeft", addClass: "size-4" }))), !isLast && (h("button", { type: "button", class: "inline-flex h-8 w-8 items-center justify-center rounded-full border-[1.5px] border-primary text-primary bg-background transition-colors hover:bg-white focus:outline-none focus:ring-2 focus:ring-slate-200 cursor-pointer", "aria-label": t('quick_message.move_right'), onClick: () => this.reorderMenu(menu.id, 'next') }, h(Icon, { name: "ChevronRight", addClass: "size-4" })))), h("button", { type: "button", class: "pointer-events-auto inline-flex h-8 w-8 items-center justify-center rounded-full bg-background text-red-500 shadow focus:outline-none focus:ring-2 focus:ring-red-200 cursor-pointer hover:bg-white", onClick: () => this.handleDeleteMenu(menu.id), "aria-label": t('remove') }, h(Icon, { name: "Trash2", addClass: "size-4" }))), h("div", { class: "group relative h-[180px] overflow-hidden border-b-[1.5px] border-primary" }, h("input", { type: "file", accept: "image/*", class: "hidden", ref: el => (this.fileInputs[menu.id] = el), onChange: event => this.handleImageChange(menu.id, event) }), (menu.file_url || menu.file?.url) ? (h(Fragment, null, !this.loadedUrls.has(menu.file_url || menu.file?.url) && (h(MediaSkeleton, null)), h("img", { src: menu.file_url || menu.file?.url, alt: menu.title || t('quick_message.add_image'), class: "h-full w-full object-cover", style: { animation: 'z-fadeIn 0.3s ease-in-out' }, onLoad: () => this.handleImageLoad(menu.file_url || menu.file?.url), onError: () => this.handleImageError(menu.file_url || menu.file?.url), loading: "lazy" }), h("div", { class: "absolute inset-0 flex items-center justify-center gap-2 bg-slate-900/60 opacity-0 transition-opacity group-hover:opacity-100" }, h("button", { type: "button", class: "inline-flex cursor-pointer items-center gap-2 rounded-full bg-white/90 px-3 py-1.5 text-xs font-semibold text-slate-700 shadow", onClick: () => this.handleSelectImage(menu.id) }, h(Icon, { name: "Image", addClass: "size-4" }), h("span", null, t('quick_message.change_image'))), h("button", { type: "button", class: "inline-flex cursor-pointer items-center gap-2 rounded-full bg-white/90 px-3 py-1.5 text-xs font-semibold text-red-500 shadow", onClick: () => this.handleRemoveImage(menu.id) }, h(Icon, { name: "Trash2", addClass: "size-4" }), h("span", null, t('remove')))))) : (h("button", { type: "button", class: "flex h-full w-full flex-col items-center justify-center gap-2 border-0 px-4 text-center text-primary bg-background cursor-pointer", onClick: () => this.handleSelectImage(menu.id) }, h(Icon, { name: "Image", addClass: "size-12" }), h("span", { class: "text-sm font-semibold leading-tight" }, "+ ", t('quick_message.add_image')), h("span", { class: "text-xs font-medium text-theme-gray" }, t('quick_message.image_size_hint'))))), h("div", { class: "flex flex-col gap-2 px-2 py-2" }, h("div", null, h("textarea", { value: title, maxLength: this.maxTitleLength, rows: 2, placeholder: t('quick_message.type_title_here'), class: "w-full resize-none border-0 bg-transparent text-sm font-semibold leading-snug focus:outline-none focus:ring-0", onInput: event => this.setMenuTitle(menu.id, event.target.value) }), h("div", { class: "text-right text-xs text-theme-gray" }, title.length, "/", this.maxTitleLength)), h("div", null, h("textarea", { value: description, maxLength: this.maxDescriptionLength, rows: 2, placeholder: t('quick_message.type_description_here'), class: "w-full resize-none border-0 bg-transparent text-xs leading-snug focus:outline-none focus:ring-0", onInput: event => this.setMenuDescription(menu.id, event.target.value) }), h("div", { class: "text-right text-xs text-theme-gray" }, description.length, "/", this.maxDescriptionLength)), h(QuickMessageTemplateButtonList, { buttons: buttons, maxButtonCount: this.maxButtonCount, addButtonLabel: t('quick_message.add_button'), onButtonClick: button => this.openButtonDialog(menu.id, button), onAddButton: () => this.openButtonDialog(menu.id), onReorderButton: (buttonId, direction) => this.reorderMenuButton(menu.id, buttonId, direction), listClass: "flex flex-col gap-2", buttonClass: "px-3" }))), error && h("p", { class: "mt-2 text-xs font-medium text-red-500" }, error)));
    }
    render() {
        if (!this.content) {
            return null;
        }
        const theme = configStore.get('theme');
        const t = useTranslation();
        const menus = this.content.menu_list || [];
        return (h("div", { class: "flex flex-col gap-3 items-end overflow-x-auto" }, h("div", { class: "flex max-w-full gap-3 pb-2" }, menus.map((menu, index) => this.renderMenuCard(menu, index, menus.length, theme, t)), menus.length < this.maxMenuList && (h("button", { type: "button", class: "flex h-[280px] w-[200px] shrink-0 items-center justify-center rounded-[18px] border-[1.5px] border-dashed text-2xl font-semibold border-primary text-primary bg-background cursor-pointer", onClick: () => this.handleAddMenu() }, h(Icon, { name: "Plus", addClass: "size-8" })))), h(QuickMessageTemplateButtonDialog, { isOpen: this.isButtonDialogOpen, isEditing: !!this.editingButtonId, label: this.buttonDialogLabel, actionValue: this.buttonDialogAction, actionType: this.buttonDialogType, maxButtonNameLength: this.maxButtonNameLength, onLabelInput: value => (this.buttonDialogLabel = value), onActionInput: value => (this.buttonDialogAction = value), onActionTypeChange: type => this.setButtonDialogType(type), onClose: () => this.closeButtonDialog(), onSave: () => this.handleButtonSave(), onDelete: this.editingButtonId ? () => this.handleDeleteButton() : undefined })));
    }
    static get is() { return "quick-message-menu-list-content"; }
    static get properties() {
        return {
            "content": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "QuickMessageTemplateContent",
                    "resolved": "{ id: string; type: QuickMessageTemplateContentType; text?: string; buttons: QuickMessageTemplateButton[]; file_url?: string; file?: FileMessage; menu_list: QuickMessageTemplateMenuListItem[]; sequence?: number; }",
                    "references": {
                        "QuickMessageTemplateContent": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplateContent",
                            "referenceLocation": "QuickMessageTemplateContent"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "maxMenuList": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "max-menu-list",
                "defaultValue": "10"
            },
            "maxTitleLength": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "max-title-length",
                "defaultValue": "80"
            },
            "maxDescriptionLength": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "max-description-length",
                "defaultValue": "80"
            },
            "maxButtonCount": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "max-button-count",
                "defaultValue": "3"
            },
            "maxButtonNameLength": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "max-button-name-length",
                "defaultValue": "20"
            }
        };
    }
    static get states() {
        return {
            "isButtonDialogOpen": {},
            "buttonDialogMenuId": {},
            "buttonDialogLabel": {},
            "buttonDialogAction": {},
            "buttonDialogType": {},
            "editingButtonId": {},
            "menuErrors": {},
            "loadedUrls": {},
            "errorUrls": {}
        };
    }
    static get events() {
        return [{
                "method": "contentChange",
                "name": "contentChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "QuickMessageTemplateContent",
                    "resolved": "{ id: string; type: QuickMessageTemplateContentType; text?: string; buttons: QuickMessageTemplateButton[]; file_url?: string; file?: FileMessage; menu_list: QuickMessageTemplateMenuListItem[]; sequence?: number; }",
                    "references": {
                        "QuickMessageTemplateContent": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::QuickMessageTemplateContent",
                            "referenceLocation": "QuickMessageTemplateContent"
                        }
                    }
                }
            }];
    }
}
