import { h } from "@stencil/core";
import { configStore } from "../../store/store";
import { setupLanguage, setupTheme, setupBusinessId, setupShopId, setupAccessToken, setupIsProduction, setupTimeZone } from "../../utils/setup";
import { getUserTags, createUserTag, updateUserTag, deleteUserTag, reorderUserTag, resequenceUserTag, } from "../../api/index";
import { ZButton } from "../internal-component/z-button";
import { ZInput } from "../internal-component/z-input";
import { Icon } from "../internal-component/icon";
import { useTranslation } from "../../utils/utils";
import { openDialog, handleError, closeDialog } from "../../store/dialog";
import Sortable from "sortablejs";
import { GET_USER_TAG_MASTER_PAGE_LIMIT } from "../../utils/constant";
export class MasterTagApp {
    languagePref = 'en';
    themeMode = 'light';
    businessId;
    shopId;
    accessToken;
    isProduction = false;
    timeZone;
    tags = [];
    searchQuery = '';
    loading = false;
    dialogOpen = false;
    editingItem = null;
    dialogLoading = false;
    containerRef;
    sortable;
    connectedCallback() {
        setupLanguage(this.languagePref);
        setupTheme(this.themeMode);
        setupBusinessId(this.businessId);
        setupShopId(this.shopId);
        setupAccessToken(this.accessToken);
        setupIsProduction(this.isProduction);
        setupTimeZone(this.timeZone);
    }
    componentWillLoad() {
        setupBusinessId(this.businessId);
        setupShopId(this.shopId);
        setupAccessToken(this.accessToken);
        setupIsProduction(this.isProduction);
        setupTimeZone(this.timeZone);
        this.fetchData();
    }
    componentDidLoad() {
        if (this.containerRef) {
            this.sortable = new Sortable(this.containerRef, {
                animation: 150,
                ghostClass: 'tag-sortable-ghost',
                handle: '.master-data-item-drag-handle',
                onEnd: async (evt) => {
                    const { oldIndex, newIndex } = evt;
                    if (oldIndex === newIndex || oldIndex === undefined || newIndex === undefined)
                        return;
                    const newTags = [...this.tags];
                    const [movedItem] = newTags.splice(oldIndex, 1);
                    newTags.splice(newIndex, 0, movedItem);
                    this.tags = newTags;
                    try {
                        await reorderUserTag({ id: movedItem.id, sequence: newIndex + 1 });
                    }
                    catch (error) {
                        handleError(error, 'Failed to reorder tag');
                        await this.fetchData(); // Revert on error
                    }
                },
            });
        }
    }
    disconnectedCallback() {
        if (this.sortable)
            this.sortable.destroy();
    }
    handleLanguageChange(newValue) {
        setupLanguage(newValue);
    }
    handleThemeChange(newValue) {
        setupTheme(newValue);
    }
    handleBusinessIdChange(newValue) {
        setupBusinessId(newValue);
        this.fetchData();
    }
    handleShopIdChange(newValue) {
        setupShopId(newValue);
        this.fetchData();
    }
    handleAccessTokenChange(newValue) {
        setupAccessToken(newValue);
        this.fetchData();
    }
    handleIsProductionChange(newValue) {
        setupIsProduction(newValue);
    }
    handleTimeZoneChange(newValue) {
        setupTimeZone(newValue);
    }
    async fetchData() {
        if (!this.businessId || !this.shopId || !this.accessToken)
            return;
        this.loading = true;
        try {
            let response = await getUserTags({ limit: GET_USER_TAG_MASTER_PAGE_LIMIT });
            const isInvalidOrder = response.tags.some((tag, index) => tag.sequence != index + 1);
            if (isInvalidOrder) {
                await resequenceUserTag();
                response = await getUserTags({ limit: GET_USER_TAG_MASTER_PAGE_LIMIT });
            }
            this.tags = response.tags.sort((a, b) => a.sequence - b.sequence);
        }
        catch (error) {
            handleError(error, 'Failed to fetch tags');
        }
        finally {
            this.loading = false;
        }
    }
    handleCreate = async (e) => {
        const t = useTranslation();
        this.dialogLoading = true;
        try {
            await createUserTag({ name: e.detail.name, color: e.detail.color });
            this.dialogOpen = false;
            openDialog({
                open: true,
                type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                title: t('success'),
                onCloseDialog: closeDialog,
            });
            await this.fetchData();
        }
        catch (error) {
            handleError(error, 'Failed to create tag');
        }
        finally {
            this.dialogLoading = false;
        }
    };
    handleUpdate = async (e) => {
        if (!this.editingItem)
            return;
        const t = useTranslation();
        this.dialogLoading = true;
        try {
            await updateUserTag({
                id: this.editingItem.id,
                name: e.detail.name,
                color: e.detail.color,
            });
            this.dialogOpen = false;
            openDialog({
                open: true,
                type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                title: t('success'),
                onCloseDialog: closeDialog,
            });
            this.editingItem = null;
            await this.fetchData();
        }
        catch (error) {
            handleError(error, 'Failed to update tag');
        }
        finally {
            this.dialogLoading = false;
        }
    };
    handleDelete = async () => {
        if (!this.editingItem)
            return;
        const t = useTranslation();
        let total;
        openDialog({
            open: true,
            type: "WARNING" /* DIALOG_TYPE.WARNING */,
            title: t('master_data.confirm_delete_tag'),
            buttonName: t('confirm'),
            cancelButtonName: t('cancel'),
            onSubmitDialog: async () => {
                try {
                    this.dialogLoading = true;
                    await deleteUserTag({ id: this.editingItem.id, });
                    openDialog({
                        open: true,
                        type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                        title: t('success'),
                        onCloseDialog: closeDialog,
                    });
                    await this.fetchData();
                }
                catch (error) {
                    if (error.response && error.response.data && error.response.data.code === 'user-tag-in-use') {
                        total = error.response.data.data ? error.response.data.data.total : undefined;
                        if (total) {
                            openDialog({
                                open: true,
                                type: "WARNING" /* DIALOG_TYPE.WARNING */,
                                title: t('quick_message.delete_item_with_users_confirmation', { total }),
                                buttonName: t('confirm'),
                                cancelButtonName: t('cancel'),
                                onSubmitDialog: async () => {
                                    try {
                                        await deleteUserTag({ id: this.editingItem.id, force: true });
                                        this.dialogOpen = false;
                                        this.editingItem = null;
                                        openDialog({
                                            open: true,
                                            type: "SUCCESS" /* DIALOG_TYPE.SUCCESS */,
                                            title: t('success'),
                                            onCloseDialog: closeDialog,
                                        });
                                        await this.fetchData();
                                    }
                                    catch (e) {
                                        handleError(e, 'Failed to delete tag');
                                    }
                                },
                            });
                        }
                    }
                    else {
                        handleError(error, 'Failed to delete tag');
                    }
                }
                finally {
                    if (!total) {
                        this.dialogOpen = false;
                        this.editingItem = null;
                        await this.fetchData();
                    }
                    this.dialogLoading = false;
                }
            }
        });
    };
    handleReorder = async (id, direction) => {
        const currentIndex = this.tags.findIndex((s) => s.id === id);
        if (currentIndex === -1)
            return;
        let newSequence = 0;
        if (direction === 'top') {
            newSequence = 1;
        }
        else {
            newSequence = this.tags.length;
        }
        const newTags = [...this.tags];
        const [movedItem] = newTags.splice(currentIndex, 1);
        newTags.splice(newSequence - 1, 0, movedItem);
        newTags.forEach((item, index) => {
            item.sequence = index;
        });
        this.tags = newTags;
        try {
            await reorderUserTag({ id, sequence: newSequence });
        }
        catch (error) {
            handleError(error, 'Failed to reorder tag');
        }
    };
    render() {
        const theme = configStore.get('theme');
        const t = useTranslation();
        const filteredTags = this.tags.filter((s) => s.name.toLowerCase().includes(this.searchQuery.toLowerCase()));
        return (h("div", { key: '862cb64d2c4a483365e35bdf90dd7d0093da6556', class: "master-tag-app", "data-theme": theme }, h("div", { key: 'a34ccf9d8bc70c0da9e0423a7928d97581fec6fe', class: "master-tag-app-header" }, h("h1", { key: 'ec5c2b35faf0228398b31b98171d659c5801a03b', class: "master-tag-app-title" }, t('tag')), h("div", { key: 'af74fced5cdbc2dbbf83e3d6895b456daee8a7da', class: "master-tag-app-controls" }, h("div", { key: '05ef18a4d90ca84ae5cc29ad7ec54b762caaea9b', class: "master-tag-app-search" }, h(ZInput, { key: '5f5ad3082115da58a6348d76a24ff1dac496d0e6', placeholder: t('master_data.search_tag'), value: this.searchQuery, onChange: (val) => (this.searchQuery = val) })), h(ZButton, { key: '3313e2ced23ceaceb568660d0131e477d524f6e8', variant: "outlined", id: "create-master-tag-button", label: t('master_data.add_tag'), onClick: () => {
                this.editingItem = null;
                this.dialogOpen = true;
            }, startIcon: h(Icon, { name: "Plus" }) }))), h("div", { key: '984a625193fd910ad1526bbda39967b49a7e66ed', class: "master-tag-app-content", ref: (el) => (this.containerRef = el) }, this.loading ? (h("div", { class: "flex justify-center items-center min-h-75" }, h(Icon, { name: "LoaderCircle", addClass: "animate-spin size-8 text-primary" }))) : filteredTags.length > 0 ? (filteredTags.map((tag, index) => (h("master-data-item", { key: tag.id, type: "tag", item: {
                id: tag.id || '',
                name: tag.name,
                color: tag.color || '',
                sequence: tag.sequence || 0
            }, index: index, isFirst: index === 0, isLast: index === filteredTags.length - 1, isSearching: !!this.searchQuery, draggableItem: !this.searchQuery, onEdit: () => {
                this.editingItem = tag;
                this.dialogOpen = true;
            }, onMoveToTop: (e) => this.handleReorder(e.detail, 'top'), onMoveToBottom: (e) => this.handleReorder(e.detail, 'bottom') })))) : (h("div", { class: "master-tag-app-empty" }, h(Icon, { name: "Tag", addClass: "master-tag-app-empty-icon" }), h("p", null, this.searchQuery
            ? t('master_data.not_found_tag')
            : t('master_data.tag_empty'))))), h("create-master-data-dialog", { key: '740cfe5aba1d1909a1110e736b0a86967bd2835e', open: this.dialogOpen, dialogTitle: t('tag'), type: "tag", initialData: this.editingItem ? {
                id: this.editingItem.id || '',
                name: this.editingItem.name,
                color: this.editingItem.color || ''
            } : undefined, loading: this.dialogLoading, onClose: () => (this.dialogOpen = false), onSubmitData: (e) => (this.editingItem ? this.handleUpdate(e) : this.handleCreate(e)), onDelete: this.handleDelete }), h("z-dialog", { key: '56c3d2ef62ba3faef77efdc9ca4657c865061f19' })));
    }
    static get is() { return "master-tag-app"; }
    static get originalStyleUrls() {
        return {
            "$": ["master-tag-app.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["master-tag-app.css"]
        };
    }
    static get properties() {
        return {
            "languagePref": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "language-pref",
                "defaultValue": "'en'"
            },
            "themeMode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'light' | 'dark'",
                    "resolved": "\"dark\" | \"light\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "theme-mode",
                "defaultValue": "'light'"
            },
            "businessId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "business-id"
            },
            "shopId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "shop-id"
            },
            "accessToken": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "access-token"
            },
            "isProduction": {
                "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-production",
                "defaultValue": "false"
            },
            "timeZone": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "time-zone"
            }
        };
    }
    static get states() {
        return {
            "tags": {},
            "searchQuery": {},
            "loading": {},
            "dialogOpen": {},
            "editingItem": {},
            "dialogLoading": {}
        };
    }
    static get watchers() {
        return [{
                "propName": "languagePref",
                "methodName": "handleLanguageChange"
            }, {
                "propName": "themeMode",
                "methodName": "handleThemeChange"
            }, {
                "propName": "businessId",
                "methodName": "handleBusinessIdChange"
            }, {
                "propName": "shopId",
                "methodName": "handleShopIdChange"
            }, {
                "propName": "accessToken",
                "methodName": "handleAccessTokenChange"
            }, {
                "propName": "isProduction",
                "methodName": "handleIsProductionChange"
            }, {
                "propName": "timeZone",
                "methodName": "handleTimeZoneChange"
            }];
    }
}
