import { Host, h } from "@stencil/core";
import { useTranslation } from "../../utils/utils";
import { ZIconButton } from "../internal-component/z-icon-button";
import { ZButton } from "../internal-component/z-button";
import { ZTagOrStatusItem } from "../internal-component/z-tag-or-status-item";
import { postCustomerTagConfigs } from "../../api/zdesk/customer";
import { handleGetUserTags } from "../../store/chat";
import { tagsStore } from "../../store/store";
import { createUserTag } from "../../api/index";
import { getConnectionId, getConnectionItem } from "../../utils/func";
import { getBusinessUser } from "./utils";
import { handleError } from "../../store/dialog";
import { DEFAULT_COLOR } from "../../utils/constant";
export class ProfileTicketTags {
    ticket;
    ticketTagsUpdated;
    isEditTag = false;
    isAddTag = false;
    tempTagItems = [];
    t = useTranslation();
    async componentWillLoad() {
        if (!tagsStore.get('tags')?.length) {
            handleGetUserTags();
        }
    }
    onSyncTagComplete() {
        handleGetUserTags();
    }
    handleEditTag = () => {
        this.isEditTag = true;
        this.isAddTag = false;
        this.tempTagItems = this.ticket.tags.map((tag, index) => {
            const storeTag = tagsStore.get('tags')?.find(t => t.name === tag.tag);
            return {
                item: {
                    id: storeTag?.id || tag.tag_id || tag.id || `temp-${index}`,
                    name: tag.tag,
                    color: storeTag?.color || DEFAULT_COLOR,
                    sequence: index
                },
                isUnmapped: !storeTag,
            };
        });
    };
    handleCloseTag = () => {
        this.isEditTag = false;
        this.isAddTag = false;
        this.tempTagItems = [];
    };
    handleDeleteTag = (tagId) => {
        this.tempTagItems = this.tempTagItems.map(t => t.item.id === tagId ? { ...t, isDelete: true } : t);
    };
    handleAddTag = (item) => {
        if (!item)
            return;
        const exists = this.tempTagItems.find(t => t.item.id === item.id || t.item.name === item.name);
        if (exists) {
            if (exists.isDelete) {
                this.tempTagItems = this.tempTagItems.map(t => (t.item.id === item.id || t.item.name === item.name) ? { ...t, isDelete: false } : t);
            }
            return;
        }
        this.tempTagItems = [...this.tempTagItems, { item, isAdd: true }];
    };
    handleSaveUserTags = async () => {
        const keptTags = this.tempTagItems.filter(t => !t.isDelete);
        const unmappedTags = keptTags.filter(t => t.isUnmapped);
        if (unmappedTags.length > 0) {
            await Promise.all(unmappedTags.map(t => createUserTag({ name: t.item.name, color: DEFAULT_COLOR }).catch(e => handleError(e, 'Failed to create unmapped user tag'))));
        }
        const finalTags = keptTags.map(t => t.item.name);
        this.ticketTagsUpdated.emit(finalTags);
        this.handleCloseTag();
    };
    createTagConfig = async (name) => {
        try {
            const connectionItem = getConnectionItem();
            const connectionId = getConnectionId(connectionItem);
            const businessUser = getBusinessUser(connectionItem);
            if (!businessUser)
                throw new Error('Business user not found');
            const [response] = await Promise.all([
                postCustomerTagConfigs({ connectionId }, { data: { business_id: businessUser.business_id, tag: name } }),
                createUserTag({ name, color: DEFAULT_COLOR })
            ]);
            return {
                id: response.id,
                name: response.tag,
            };
        }
        catch (error) {
            handleError(error, 'Failed to create tag config');
            throw error;
        }
    };
    render() {
        return (h(Host, { key: '1bb25a20d01dbeb2e4252081b150923e6424c0dc' }, h("div", { key: 'b44c5cddcfdf38536f8483a7c4cef5866c63eedd', class: "space-y-3" }, h("div", { key: '82eb1c0b52936772f44286aa4affccfc8c7018c1', class: "flex items-center justify-between" }, h("span", { key: 'd3d27f4532b7d0dc721a51507ca2a9c2de9d5576', class: "text-surface font-semibold" }, this.t('ticket_field.tags')), !this.isEditTag ? (h(ZIconButton, { variant: "text", iconName: "Pencil", addClassIcon: "size-4 text-primary", noPadding: true, noPaddingY: true, onClick: this.handleEditTag })) : (h("div", { class: "flex items-center gap-2" }, h(ZIconButton, { variant: "text", iconName: "X", addClassIcon: "size-4 text-primary", noPadding: true, noPaddingY: true, onClick: this.handleCloseTag }), h(ZIconButton, { variant: "text", iconName: "Save", addClassIcon: "size-4 text-primary", noPadding: true, noPaddingY: true, onClick: this.handleSaveUserTags })))), h("div", { key: '3533d128a29392311d88871932b921f3314091ab', class: "flex flex-wrap gap-2" }, !this.isEditTag ? (this.ticket.tags.map(tag => {
            const storeTag = tagsStore.get('tags')?.find(t => t.name === tag.tag);
            return (h("tag-or-status-item", { chatId: this.ticket.id.toString(), item: {
                    id: storeTag?.id || tag.tag_id || tag.id || tag.tag,
                    name: tag.tag,
                    color: storeTag?.color || DEFAULT_COLOR
                } }));
        })) : (h("div", { class: "w-full" }, h("div", { class: "flex flex-wrap gap-2" }, this.tempTagItems
            .filter(({ isDelete }) => !isDelete)
            .map(tag => (h(ZTagOrStatusItem, { item: tag.item, onDelete: () => this.handleDeleteTag(tag.item.id) })))), h("div", { class: "mt-2" }, this.isAddTag ? (h("autocomplete-select", { referenceSelector: "ticket-tag-select", type: "tag", selectedIds: this.tempTagItems.filter(({ isDelete }) => !isDelete).map(({ item }) => item.id), fetchItems: handleGetUserTags, createItem: name => this.createTagConfig(name), onSelecting: e => this.handleAddTag(e.detail) })) : (h(ZButton, { variant: "outlined", fullWidth: true, label: `+ ${this.t('profile_tab.add_tag')}`, onClick: () => this.isAddTag = true })))))))));
    }
    static get is() { return "profile-ticket-tags"; }
    static get properties() {
        return {
            "ticket": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "ITicket",
                    "resolved": "ITicket",
                    "references": {
                        "ITicket": {
                            "location": "import",
                            "path": "../../store/zdesk.type",
                            "id": "src/store/zdesk.type.ts::ITicket",
                            "referenceLocation": "ITicket"
                        }
                    }
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            }
        };
    }
    static get states() {
        return {
            "isEditTag": {},
            "isAddTag": {},
            "tempTagItems": {}
        };
    }
    static get events() {
        return [{
                "method": "ticketTagsUpdated",
                "name": "ticketTagsUpdated",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string[]",
                    "resolved": "string[]",
                    "references": {}
                }
            }];
    }
    static get listeners() {
        return [{
                "name": "syncTagComplete",
                "method": "onSyncTagComplete",
                "target": "window",
                "capture": false,
                "passive": false
            }];
    }
}
