import { h } from "@stencil/core";
import { configStore } from "../../store/store";
import { setupLanguage, setupTheme, setupBusinessId, setupShopId, setupAccessToken, setupIsProduction, setupTimeZone } from "../../utils/setup";
import { getUserStatuses, createUserStatus, updateUserStatus, deleteUserStatus, reorderUserStatus, resequenceUserStatus, } 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";
export class MasterStatusApp {
    languagePref = 'en';
    themeMode = 'light';
    businessId;
    shopId;
    accessToken;
    isProduction = false;
    timeZone;
    statuses = [];
    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: 'status-sortable-ghost',
                handle: '.master-data-item-drag-handle',
                onEnd: async (evt) => {
                    const { oldIndex, newIndex } = evt;
                    if (oldIndex === newIndex || oldIndex === undefined || newIndex === undefined)
                        return;
                    const newStatuses = [...this.statuses];
                    const [movedItem] = newStatuses.splice(oldIndex, 1);
                    newStatuses.splice(newIndex, 0, movedItem);
                    this.statuses = newStatuses;
                    try {
                        await reorderUserStatus({ id: movedItem.id, sequence: newIndex + 1 });
                    }
                    catch (error) {
                        handleError(error, 'Failed to reorder status');
                        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 getUserStatuses();
            const isInvalidOrder = response.statuses.some((status, index) => status.sequence !== index + 1);
            if (isInvalidOrder) {
                await resequenceUserStatus();
                response = await getUserStatuses();
            }
            this.statuses = response.statuses.sort((a, b) => a.sequence - b.sequence);
        }
        catch (error) {
            handleError(error, 'Failed to fetch statuses');
        }
        finally {
            this.loading = false;
        }
    }
    handleCreate = async (e) => {
        const t = useTranslation();
        this.dialogLoading = true;
        try {
            await createUserStatus({ 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 status');
        }
        finally {
            this.dialogLoading = false;
        }
    };
    handleUpdate = async (e) => {
        if (!this.editingItem)
            return;
        const t = useTranslation();
        this.dialogLoading = true;
        try {
            await updateUserStatus({
                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 status');
        }
        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_status'),
            buttonName: t('confirm'),
            cancelButtonName: t('cancel'),
            onSubmitDialog: async () => {
                try {
                    this.dialogLoading = true;
                    await deleteUserStatus({ 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-status-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 deleteUserStatus({ 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 status');
                                    }
                                },
                            });
                        }
                    }
                    else {
                        handleError(error, 'Failed to delete status');
                    }
                }
                finally {
                    if (!total) {
                        this.dialogOpen = false;
                        this.editingItem = null;
                        await this.fetchData();
                    }
                    this.dialogLoading = false;
                }
            }
        });
    };
    handleReorder = async (id, direction) => {
        const currentIndex = this.statuses.findIndex((s) => s.id === id);
        if (currentIndex === -1)
            return;
        let newSequence = 0;
        if (direction === 'top') {
            newSequence = 1;
        }
        else {
            newSequence = this.statuses.length;
        }
        const newStatuses = [...this.statuses];
        const [movedItem] = newStatuses.splice(currentIndex, 1);
        newStatuses.splice(newSequence - 1, 0, movedItem);
        newStatuses.forEach((item, index) => {
            item.sequence = index;
        });
        this.statuses = newStatuses;
        try {
            await reorderUserStatus({ id, sequence: newSequence });
        }
        catch (error) {
            handleError(error, 'Failed to reorder status');
        }
    };
    render() {
        const theme = configStore.get('theme');
        const t = useTranslation();
        const filteredStatuses = this.statuses.filter((s) => s.name.toLowerCase().includes(this.searchQuery.toLowerCase()));
        return (h("div", { key: '3a5d639de0aa80e5736fec8b0b9e258fe1d33fa9', "data-theme": theme, class: "master-status-app" }, h("div", { key: 'e772c7a5205a18cd20b09a6014fe6efa74ac27e7', class: "master-status-app-header" }, h("h1", { key: '02a39b7aaef1d332ebd0ed68e1820a75b12121d3', class: "master-status-app-title" }, t('status')), h("div", { key: 'aa11436ebbd46ced204ca68ce8224a452afe70bb', class: "master-status-app-controls" }, h("div", { key: '8b77423540d08d11b92643e5d8f822fd532bc360', class: "master-status-app-search" }, h(ZInput, { key: '8a760632e689f1b6cf541045759c576beaeef565', placeholder: t('master_data.search_status'), value: this.searchQuery, onChange: (val) => (this.searchQuery = val) })), h(ZButton, { key: '7ec4910d5314370b8549bafee7ed94ca8ca38a87', variant: "outlined", id: "create-master-status-button", label: t('master_data.add_status'), onClick: () => {
                this.editingItem = null;
                this.dialogOpen = true;
            }, startIcon: h(Icon, { name: "Plus" }) }))), h("div", { key: '17927e85d9434b1cb66eecd075a2703a38321d23', class: "master-status-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" }))) : filteredStatuses.length > 0 ? (filteredStatuses.map((status, index) => (h("master-data-item", { key: status.id, type: "status", item: {
                id: status.id || '',
                name: status.name,
                color: status.color || '',
                sequence: status.sequence || 0
            }, index: index, isFirst: index === 0, isLast: index === filteredStatuses.length - 1, isSearching: !!this.searchQuery, draggableItem: !this.searchQuery, onEdit: () => {
                this.editingItem = status;
                this.dialogOpen = true;
            }, onMoveToTop: (e) => this.handleReorder(e.detail, 'top'), onMoveToBottom: (e) => this.handleReorder(e.detail, 'bottom') })))) : (h("div", { class: "master-status-app-empty" }, h(Icon, { name: "ClipboardList", addClass: "master-status-app-empty-icon" }), h("p", null, this.searchQuery
            ? t('master_data.not_found_status')
            : t('master_data.status_empty'))))), h("create-master-data-dialog", { key: 'cfc6d616aa9775736926ae2d00e1c55fab2c5e1d', open: this.dialogOpen, dialogTitle: t('status'), type: "status", 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: 'a1e718993f2a3f2b62c09f2f5678734ed06127e5' })));
    }
    static get is() { return "master-status-app"; }
    static get originalStyleUrls() {
        return {
            "$": ["master-status-app.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["master-status-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 {
            "statuses": {},
            "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"
            }];
    }
}
