import { h } from "@stencil/core";
import { configStore } from "../../store/store";
import { useTranslation } from "../../utils/utils";
import { QuickMessageTemplateButtonList } from "./quick-message-template-button-list";
import { QuickMessageTemplateButtonDialog } from "./quick-message-template-button-dialog";
import { isValidTelephoneNumber, isValidUrl } from "../../utils/validators";
export class QuickMessageButtonContentComponent {
    content;
    maxLength = 640;
    maxButtonCount = 3;
    maxButtonNameLength = 20;
    placeholder = 'พิมพ์ข้อความที่นี่';
    contentChange;
    isShowCreateButtonDialog = false;
    createButtonLabel = '';
    createButtonAction = '';
    createButtonType = 'text';
    editingButtonId;
    emitContent(update) {
        if (!this.content) {
            return;
        }
        this.contentChange.emit({ ...this.content, ...update });
    }
    updateButtons(updater) {
        if (!this.content) {
            return;
        }
        const currentButtons = this.content.buttons || [];
        const nextButtons = updater(currentButtons);
        this.emitContent({ buttons: nextButtons });
    }
    reorderButtons(buttonId, direction) {
        this.updateButtons(current => {
            const index = current.findIndex(button => button.id === buttonId);
            if (index === -1) {
                return current;
            }
            const targetIndex = direction === 'up' ? index - 1 : index + 1;
            if (targetIndex < 0 || targetIndex >= current.length) {
                return current;
            }
            const nextButtons = [...current];
            [nextButtons[index], nextButtons[targetIndex]] = [nextButtons[targetIndex], nextButtons[index]];
            return nextButtons;
        });
    }
    handleTextChange = (event) => {
        const target = event.target;
        this.emitContent({ text: target.value });
    };
    openCreateButtonDialog(button) {
        if (button) {
            this.editingButtonId = button.id;
            this.createButtonLabel = button.text || '';
            this.createButtonAction = button.action || '';
            this.createButtonType = button.action_type;
        }
        else {
            this.editingButtonId = undefined;
            this.createButtonLabel = '';
            this.createButtonAction = '';
            this.createButtonType = 'text';
        }
        this.isShowCreateButtonDialog = true;
    }
    closeCreateButtonDialog() {
        this.isShowCreateButtonDialog = false;
        this.editingButtonId = undefined;
    }
    handleCreateButtonSave() {
        const label = this.createButtonLabel.trim();
        const actionType = this.createButtonType;
        const trimmedActionValue = this.createButtonAction.trim();
        const actionValue = actionType === 'text' ? undefined : trimmedActionValue;
        const isActionInvalid = actionType !== 'text' &&
            (!trimmedActionValue || (actionType === 'url' && !isValidUrl(trimmedActionValue)) || (actionType === 'tel' && !isValidTelephoneNumber(trimmedActionValue)));
        if (!label || isActionInvalid) {
            return;
        }
        if (this.editingButtonId) {
            const updatedButton = {
                id: this.editingButtonId,
                action_type: actionType,
                text: label,
                action: actionValue,
            };
            this.updateButtons(current => current.map(button => (button.id === this.editingButtonId ? updatedButton : button)));
        }
        else {
            const newButton = {
                id: `button-${Date.now()}`,
                action_type: actionType,
                text: label,
                action: actionValue,
            };
            this.updateButtons(current => [...current, newButton]);
        }
        this.closeCreateButtonDialog();
    }
    setCreateButtonType(type) {
        this.createButtonType = type;
        if (type === 'text') {
            this.createButtonAction = '';
        }
    }
    handleDeleteEditingButton() {
        if (!this.editingButtonId) {
            return;
        }
        this.updateButtons(current => current.filter(button => button.id !== this.editingButtonId));
        this.closeCreateButtonDialog();
    }
    render() {
        if (!this.content) {
            return null;
        }
        const theme = configStore.get('theme');
        const text = this.content.text || '';
        const buttons = this.content.buttons || [];
        const t = useTranslation();
        return (h("div", { class: "flex flex-col gap-4 items-end", "data-theme": theme }, h("div", { class: `relative w-full max-w-md rounded-xl border-[1.5px] p-4 pb-8 focus:outline-none ring-primary border-primary` }, h("textarea", { value: text, onInput: this.handleTextChange, placeholder: this.placeholder, class: `w-full border-primary pr-16 focus:outline-none ring-primary rounded-xl text-sm bg-background`, maxLength: this.maxLength, rows: 3 }), h("div", { class: `flex items-center justify-end text-sm text-theme-gray` }, text.length, "/", this.maxLength), h(QuickMessageTemplateButtonList, { buttons: buttons, maxButtonCount: this.maxButtonCount, addButtonLabel: t('quick_message.add_button'), onButtonClick: button => this.openCreateButtonDialog(button), onAddButton: () => this.openCreateButtonDialog(), onReorderButton: (buttonId, direction) => this.reorderButtons(buttonId, direction), listClass: "mt-2 flex flex-col gap-3", buttonClass: "px-2" }), h(QuickMessageTemplateButtonDialog, { isOpen: this.isShowCreateButtonDialog, isEditing: !!this.editingButtonId, label: this.createButtonLabel, actionValue: this.createButtonAction, actionType: this.createButtonType, maxButtonNameLength: this.maxButtonNameLength, onLabelInput: value => (this.createButtonLabel = value), onActionInput: value => (this.createButtonAction = value), onActionTypeChange: type => this.setCreateButtonType(type), onClose: () => this.closeCreateButtonDialog(), onSave: () => this.handleCreateButtonSave(), onDelete: this.editingButtonId ? () => this.handleDeleteEditingButton() : undefined }))));
    }
    static get is() { return "quick-message-button-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
            },
            "maxLength": {
                "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-length",
                "defaultValue": "640"
            },
            "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"
            },
            "placeholder": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "placeholder",
                "defaultValue": "'\u0E1E\u0E34\u0E21\u0E1E\u0E4C\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E17\u0E35\u0E48\u0E19\u0E35\u0E48'"
            }
        };
    }
    static get states() {
        return {
            "isShowCreateButtonDialog": {},
            "createButtonLabel": {},
            "createButtonAction": {},
            "createButtonType": {},
            "editingButtonId": {}
        };
    }
    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"
                        }
                    }
                }
            }];
    }
}
