import { h } from "@stencil/core";
import { ZIconButton } from "../internal-component/z-icon-button";
import { ZButton } from "../internal-component/z-button";
import { ZContextInput } from "../internal-component/z-context-input";
export class SummarizeMessageSection {
    user;
    readOnly = false;
    activeTabIndex;
    isEditSummarizeMessage;
    summarizeMessageItems = [];
    items = [];
    expandedItemIds = [];
    truncatableItemIds = [];
    el;
    editSummarizeMessage;
    cancelSummarizeMessage;
    saveUserSummarizeMessage;
    async componentWillLoad() {
        this.syncItemsFromUser();
    }
    handleEditChange(newValue) {
        if (newValue) {
            this.syncItemsFromUser();
        }
        else {
            this.expandedItemIds = [];
            this.truncatableItemIds = [];
        }
    }
    syncItemsFromUser() {
        const messages = this.user?.summarize_messages || [];
        this.items = messages
            .map(item => ({ item: { ...item }, isAdd: false, isDelete: false }))
            .sort((a, b) => (a.item.name || '').localeCompare(b.item.name || '', 'th'));
    }
    toggleExpand = (id) => {
        if (this.expandedItemIds.includes(id)) {
            this.expandedItemIds = this.expandedItemIds.filter(i => i !== id);
        }
        else {
            this.expandedItemIds = [...this.expandedItemIds, id];
        }
    };
    componentDidRender() {
        if (!this.isEditSummarizeMessage && this.user?.summarize_messages?.length > 0) {
            setTimeout(() => {
                let changed = false;
                const newTruncatable = [...this.truncatableItemIds];
                const textEls = this.el.querySelectorAll('[data-text-id]');
                textEls.forEach((el) => {
                    const id = el.getAttribute('data-text-id');
                    if (id && !this.expandedItemIds.includes(id)) {
                        // Check if text is overflowing its 3-line container
                        const isTruncated = el.scrollHeight > el.clientHeight;
                        if (isTruncated && !newTruncatable.includes(id)) {
                            newTruncatable.push(id);
                            changed = true;
                        }
                    }
                });
                if (changed) {
                    this.truncatableItemIds = newTruncatable;
                }
            }, 50);
        }
    }
    render() {
        const renderUserContext = (item, isEdit) => {
            return (h(ZContextInput, { keyInput: {
                    id: item.item.id,
                    placeholder: 'หัวข้อ',
                    value: item.item.name,
                    disabled: !isEdit,
                    onChange: (value) => {
                        this.items = this.items.map(i => {
                            if (i.item.id === item.item.id) {
                                return {
                                    ...i,
                                    item: {
                                        ...i.item,
                                        name: value
                                    }
                                };
                            }
                            return i;
                        });
                    }
                }, valueInput: {
                    id: item.item.id,
                    placeholder: 'รายละเอียด',
                    value: item.item.value,
                    disabled: !isEdit,
                    onChange: (value) => {
                        this.items = this.items.map(i => {
                            if (i.item.id === item.item.id) {
                                return {
                                    ...i,
                                    item: {
                                        ...i.item,
                                        value: value
                                    }
                                };
                            }
                            return i;
                        });
                    }
                }, onDelete: !isEdit
                    ? undefined
                    : () => this.items = this.items.filter(it => item.item.id !== it.item.id) }));
        };
        return (h("div", { class: "profile-info-user-wrapper border-b-[0.5px] pt-2 gap-y-1 border-divider" }, h("div", { class: "col-span-3 profile-info-box-wrapper" }, h("span", { class: "text-surface whitespace-nowrap" }, "\u0E2A\u0E23\u0E38\u0E1B\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25"), !this.readOnly && this.activeTabIndex === 0 && (h("slot", null, this.isEditSummarizeMessage ? (h("div", { class: "profile-info-box-wrapper justify-end w-full" }, h(ZIconButton, { variant: "text", iconName: "X", addClassIcon: "size-4", onClick: () => this.cancelSummarizeMessage.emit() }), h(ZIconButton, { variant: "text", iconName: "Save", addClassIcon: "size-4", onClick: () => {
                const sortedItems = [...this.items].sort((a, b) => (a.item.name || '').localeCompare(b.item.name || '', 'th'));
                this.saveUserSummarizeMessage.emit(sortedItems);
            } }))) : (h("div", { class: "profile-info-box-wrapper justify-end w-full" }, h(ZIconButton, { variant: "text", iconName: "Pencil", addClassIcon: "size-4", onClick: () => this.editSummarizeMessage.emit() })))))), h("div", { class: "col-span-3 w-full" }, this.isEditSummarizeMessage ? (h("div", { class: "col-span-3" }, h("div", { class: "mb-2" }, h(ZButton, { variant: "outlined", fullWidth: true, label: "\u0E40\u0E1E\u0E34\u0E48\u0E21", onClick: () => {
                const id = new Date().getTime().toString();
                const minSequence = this.items.length > 0
                    ? Math.min(...this.items.map(i => i.item.sequence || 0))
                    : 0;
                this.items = [
                    {
                        item: {
                            id,
                            name: '',
                            sequence: minSequence - 1
                        },
                        isAdd: true
                    },
                    ...this.items
                ];
                setTimeout(() => {
                    const keyInputElement = document.getElementById("Key_" + id);
                    if (keyInputElement) {
                        keyInputElement.focus();
                    }
                }, 300);
            } })), h("div", { class: "mt-2" }, h("div", { class: "flex flex-col w-full" }, this.items.length > 0 &&
            this.items
                .filter(({ isDelete }) => !isDelete)
                .map((item) => renderUserContext(item, true)))))) : (h("div", { class: "col-span-3" }, h("div", { class: "flex flex-col w-full" }, this.user.summarize_messages && this.user.summarize_messages.length > 0 ? ([...this.user.summarize_messages]
            .sort((a, b) => (a.name || '').localeCompare(b.name || '', 'th'))
            .map(item => {
            const itemId = item.id || item.name;
            const isExpanded = this.expandedItemIds.includes(itemId);
            return (h("div", { class: "py-2 border-b-[0.5px] border-divider last:border-0 flex flex-col gap-1" }, h("div", { class: "font-bold text-surface text-base" }, item.name), h("div", { "data-text-id": itemId, class: `text-surface text-sm whitespace-pre-wrap ${isExpanded ? '' : 'line-clamp-3'}` }, item.value), this.truncatableItemIds.includes(itemId) && (h("div", { class: "flex justify-end mt-1" }, h("span", { class: "text-theme-gray cursor-pointer text-sm underline", onClick: () => this.toggleExpand(itemId) }, isExpanded ? 'ซ่อน' : 'แสดงเพิ่ม')))));
        })) : (h("span", { class: "text-sm text-theme-gray" }, "-"))))))));
    }
    static get is() { return "summarize-message-section"; }
    static get originalStyleUrls() {
        return {
            "$": ["profile-info.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["profile-info.css"]
        };
    }
    static get properties() {
        return {
            "user": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "UserItem",
                    "resolved": "{ id: string; channel: ChannelType; user_id?: string; picture_url?: string; name: string; nickname: string; email?: string | string[]; phone_number?: string | string[]; address?: UserAddress; gender?: string; locale: string; note?: string; status?: TTagOrStatusItem; tags: TTagOrStatusItem[]; last_active_at: Date; created_at: Date; created_by: string; last_updated_at: Date; last_updated_by: string; summarized_message?: UserSummarizedMessage; match_users?: MatchUserItem[]; zignal_user_id?: string; associated_users?: AssociatedUser[]; context?: string; summarize_messages: TTagOrStatusItem[]; session?: UserSession; }",
                    "references": {
                        "UserItem": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::UserItem",
                            "referenceLocation": "UserItem"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "readOnly": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "read-only",
                "defaultValue": "false"
            },
            "activeTabIndex": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "active-tab-index"
            },
            "isEditSummarizeMessage": {
                "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-edit-summarize-message"
            },
            "summarizeMessageItems": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "{\n    item: TTagOrStatusItem;\n    isAdd?: boolean;\n    isDelete?: boolean;\n  }[]",
                    "resolved": "{ item: TTagOrStatusItem; isAdd?: boolean; isDelete?: boolean; }[]",
                    "references": {
                        "TTagOrStatusItem": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::TTagOrStatusItem",
                            "referenceLocation": "TTagOrStatusItem"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            }
        };
    }
    static get states() {
        return {
            "items": {},
            "expandedItemIds": {},
            "truncatableItemIds": {}
        };
    }
    static get events() {
        return [{
                "method": "editSummarizeMessage",
                "name": "editSummarizeMessage",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "cancelSummarizeMessage",
                "name": "cancelSummarizeMessage",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "saveUserSummarizeMessage",
                "name": "saveUserSummarizeMessage",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{\n    item: TTagOrStatusItem;\n    isAdd?: boolean;\n    isDelete?: boolean;\n  }[]",
                    "resolved": "{ item: TTagOrStatusItem; isAdd?: boolean; isDelete?: boolean; }[]",
                    "references": {
                        "TTagOrStatusItem": {
                            "location": "import",
                            "path": "../../store/type",
                            "id": "src/store/type.ts::TTagOrStatusItem",
                            "referenceLocation": "TTagOrStatusItem"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "isEditSummarizeMessage",
                "methodName": "handleEditChange"
            }];
    }
}
