import { Fragment, h } from "@stencil/core";
import { ZButton } from "../internal-component/z-button";
import { ZInput } from "../internal-component/z-input";
import { ZDatePicker } from "../internal-component/z-date-picker";
import { Icon } from "../internal-component/icon";
import { t } from "i18next";
import { getZervaShopProfileSetting, getBranches, getAllServiceList } from "../../api/platform";
import { handleError } from "../../store/dialog";
import { EnumBookingStatus, EnumPaymentStatus } from "../../utils/constant";
export class SearchFilterZerva {
    filter;
    shopList = [];
    isShowAdvanced = false;
    zervaProfile = null;
    branches = [];
    serviceSettings = {};
    filterChange;
    handleToggleAdvanced = () => {
        this.isShowAdvanced = !this.isShowAdvanced;
    };
    async componentWillLoad() {
        if (this.filter?.businessId) {
            await this.getShopProfile(this.filter.businessId);
            if (this.filter.shopId) {
                await this.fetchBranchesAndServices(this.filter.businessId, this.filter.shopId);
            }
        }
    }
    handleChange = (field, value) => {
        this.filterChange.emit({
            ...this.filter,
            [field]: value,
        });
    };
    getShopProfile = async (businessId) => {
        if (businessId) {
            try {
                const { result: { shop_profile_setting } } = await getZervaShopProfileSetting(businessId);
                this.zervaProfile = shop_profile_setting?.[0];
                return shop_profile_setting?.[0];
            }
            catch (error) {
                handleError(error, 'Failed to get Zerva Shop Profile');
            }
        }
        else {
            this.zervaProfile = null;
            return null;
        }
    };
    fetchBranchesAndServices = async (businessId, shopId) => {
        try {
            const [branchesResponse, serviceResponse] = await Promise.all([
                getBranches({ businessId, shopId }),
                getAllServiceList({ businessId, shopId }),
            ]);
            this.branches = branchesResponse.branches || [];
            this.serviceSettings = serviceResponse.result?.service_settings || {};
        }
        catch (error) {
            handleError(error, 'Failed to get branches/services');
            this.branches = [];
            this.serviceSettings = {};
        }
    };
    get branchOptions() {
        const items = this.branches.map(b => ({
            value: b.id,
            label: b.name,
        }));
        items.push({
            value: 'null',
            label: t('chat_filter.no_branch'),
        });
        return items;
    }
    get filteredServiceOptions() {
        const selectedBranchIds = this.filter?.branchIds ?? [];
        return Object.entries(this.serviceSettings)
            .filter(([, service]) => {
            if (selectedBranchIds.length === 0)
                return true;
            const branchId = service.branch?.id ?? 'null';
            return selectedBranchIds.includes(branchId);
        })
            .map(([key, service]) => ({
            value: key,
            label: service.name,
        }));
    }
    handleBranchChange = (selectedIds) => {
        const validServiceIds = new Set(this.filteredServiceOptions.map(s => s.value));
        const currentServiceIds = this.filter?.serviceIds ?? [];
        const filteredServiceIds = currentServiceIds.filter(id => validServiceIds.has(id));
        const subIds = this.calculateSubIds(filteredServiceIds);
        this.filterChange.emit({
            ...this.filter,
            branchIds: selectedIds,
            serviceIds: filteredServiceIds,
            subIds,
        });
    };
    handleServiceChange = (selectedIds) => {
        const subIds = this.calculateSubIds(selectedIds);
        this.filterChange.emit({
            ...this.filter,
            serviceIds: selectedIds,
            subIds,
        });
    };
    calculateSubIds(serviceIds) {
        return serviceIds.flatMap(id => {
            const service = this.serviceSettings[id];
            if (!service?.sub_settings)
                return [];
            return Object.keys(service.sub_settings);
        });
    }
    render() {
        const isOnlyCustomers = this.filter ? this.filter.isOnlyCustomers : false;
        const filterZerva = this.filter;
        return (h("div", { key: '8a8c956bb559ddc285856db938bdafe3cc2793f8', class: "zerva-filter mt-1 flex flex-col items-start" }, h("img", { key: '1db0b1f5418f6078735d673e2b6d58dd41c61002', src: "https://zwizai-platform.s3.ap-southeast-1.amazonaws.com/zignal-package/zerva.png", alt: "zerva", class: "h-[40px] w-auto object-contain self-start", loading: "lazy" }), h("div", { key: '310c5dfd074c6850032fab41cb7a889d3d42409e', class: "flex items-center gap-2 w-full" }, h("label", { key: 'fa1876ae577c82fa3ac6bd1c794d5f9ef291704d', class: "flex-1 inline-flex items-center gap-2 text-sm mt-1 text-surface" }, h("input", { key: '0f3974da545d05bc192147a539ff0bfee4dee7ba', type: "checkbox", class: "search-filter-checkbox", checked: isOnlyCustomers, onChange: () => {
                const newValue = !isOnlyCustomers;
                if (newValue) {
                    this.filterChange.emit({
                        ...this.filter,
                        isOnlyCustomers: true,
                        businessId: null,
                        shopId: null,
                        branchIds: [],
                        serviceIds: [],
                        subIds: [],
                    });
                    this.zervaProfile = null;
                    this.branches = [];
                    this.serviceSettings = {};
                }
                else {
                    this.handleChange('isOnlyCustomers', false);
                }
            } }), h("span", { key: 'b0e373b6d67c28a7eccc0f2ded2887860ac5d220', class: "text-surface" }, t('chat_filter.only_customer_zerva'))), h(ZButton, { key: '35930eebb49c1a45eb6259cc422a852dd620c356', label: t('chat_tab.advance_search'), variant: "text-underline", endIcon: h(Icon, { name: 'Triangle', addClass: `ml-1 size-1.5 fill-current ${this.isShowAdvanced ? 'rotate-0' : 'rotate-180'}` }), disabled: isOnlyCustomers, onClick: this.handleToggleAdvanced })), this.isShowAdvanced && (h("div", { key: '8c8788d43063a94cfee95fbc96e2c98a7077685e', class: "flex flex-col mt-2 w-full" }, h("z-dropdown-input", { key: 'b92eb94af9a52ba9477f8efb1af25050ccd99eca', value: filterZerva?.businessId, options: this.shopList, onValueChange: async (event) => {
                const isOnlyCustomers = filterZerva?.isOnlyCustomers ?? false;
                if (event.detail) {
                    const profile = await this.getShopProfile(event.detail);
                    const shopId = profile?.id || null;
                    this.filterChange.emit({
                        ...filterZerva,
                        isOnlyCustomers,
                        businessId: event.detail,
                        shopId,
                        branchIds: [],
                        serviceIds: [],
                        subIds: [],
                    });
                    if (event.detail && shopId) {
                        await this.fetchBranchesAndServices(event.detail, shopId);
                    }
                }
                else {
                    this.filterChange.emit({
                        ...filterZerva,
                        isOnlyCustomers,
                        businessId: null,
                        shopId: null,
                        branchIds: [],
                        serviceIds: [],
                        subIds: [],
                    });
                    this.branches = [];
                    this.serviceSettings = {};
                }
            }, placeholder: t('chat_filter.shop_name'), class: "mb-2", enableSearch: false, showClearButton: true, disabled: isOnlyCustomers }), h("div", { key: 'a4f28f234e4c537f0a07d1dd7bee7a0c340c8ced', class: 'h-[4px]' }), filterZerva?.businessId && !isOnlyCustomers && (h(Fragment, { key: '7eb47afcea882a8522adf5bd25c18a5a30221e50' }, h(ZInput, { key: 'f485fe4f0823771f881570f14e486e10f2bd1dd5', placeholder: t('chat_filter.booking_no'), value: filterZerva ? filterZerva.bookingNo : '', onChange: value => this.handleChange('bookingNo', value), disabled: isOnlyCustomers }), h("div", { key: '1c88f0e64d494629b213afcc3ae3552d99d73624', class: 'h-[4px]' }), h(ZInput, { key: 'eb49e88fc2dd71027e59d98bf1e0636e356e6ccf', placeholder: t('chat_filter.name'), value: filterZerva ? filterZerva.name : '', onChange: value => this.handleChange('name', value), disabled: isOnlyCustomers }), h("div", { key: 'fda21f5f6579e27165b0f944facd512e01b3c8ef', class: 'h-[4px]' }), h("div", { key: 'd663a788e3f8e1ae0ba0fc0011d679e90d986a99', class: "flex w-full gap-2" }, h("div", { key: '9099a417671a7f7d139200f589e2109c3a56cc75', class: "flex-1" }, h(ZInput, { key: '2aa8ac572b20644b019b6f431a0e20b8ed8f1498', placeholder: t('quick_message.button_action_tel'), value: filterZerva ? filterZerva.phoneNumber : '', onChange: value => this.handleChange('phoneNumber', value), disabled: isOnlyCustomers })), h("div", { key: '3c5b3cbada85d17c5c306f23e7e56d7395980d2d', class: "flex-1" }, h(ZInput, { key: 'e2c11eba96718c21f994e76ee59be544ebb24170', placeholder: t('email'), value: filterZerva ? filterZerva.email : '', onChange: value => this.handleChange('email', value), disabled: isOnlyCustomers }))), h("p", { key: '92bf8056378483dd16aa1dddbf591a52490442a4', class: "text-sm mb-1 ml-1 text-surface mt-2" }, t('chat_filter.branch')), h("div", { key: '2bbae72e7ea067a4bc0e86ff082813777a30d280', class: 'mb-2', id: "zerva-filter-branch" }, h("z-multi-dropdown-input", { key: '38fd2e47b29c7931f617d68a2a698aa4ba3842cb', value: filterZerva?.branchIds ?? [], options: this.branchOptions, onValueChange: event => this.handleBranchChange(event.detail), placeholder: t('chat_filter.branch'), showClearButton: true })), h("p", { key: '9571b7998e45f388a776ebe1ea0a1242b6086c74', class: "text-sm mb-1 ml-1 text-surface mt-2" }, t('chat_filter.service')), h("div", { key: 'b25f939185d0acec0882256f2cb6faf51a88fef4', class: 'mb-2', id: "zerva-filter-service" }, h("z-multi-dropdown-input", { key: '3c040b0a1280ddf121be870306c02896a8826213', value: filterZerva?.serviceIds ?? [], options: this.filteredServiceOptions, onValueChange: event => this.handleServiceChange(event.detail), placeholder: t('chat_filter.service'), showClearButton: true })), h("p", { key: '6988bfbd0f11d99350c5415bd4a7e3f479ac3b70', class: "text-sm mb-1 ml-1 text-surface mt-2" }, t('chat_filter.service_date')), h("div", { key: 'd740a9d2c8f7dfd97d1b41b826d2b6f3d623266e', class: "flex w-full gap-2" }, h("div", { key: '0b625eecd8b8798289cfa97a2802fb5e0a43d845', class: "flex-1" }, h(ZDatePicker, { key: '60c03b9a7fa2e42f4cde736efe47d66913c97400', placeholder: t('chat_filter.start_date'), value: filterZerva ? filterZerva.bookingStartDate : null, onChange: value => this.handleChange('bookingStartDate', value), disabled: isOnlyCustomers })), h("div", { key: 'c880fca241ca67233814d37fc3a350690e4a3b73', class: "flex-1" }, h(ZDatePicker, { key: '94da88ab00ac3cda46433b37710877fb2d699f65', placeholder: t('chat_filter.end_date'), value: filterZerva ? filterZerva.bookingEndDate : null, onChange: value => this.handleChange('bookingEndDate', value), disabled: isOnlyCustomers }))), h("p", { key: 'f5474963893c10fd032add0cd97588950aca9ca7', class: "text-sm mb-1 ml-1 text-surface mt-2" }, t('status')), h("div", { key: '049973b3e75f9217a0430fd816f84124e76f7174', class: "flex w-full gap-2" }, h("div", { key: '9639c2305f0c17b06aa048e2e036f5ad9ecb3301', class: "flex-1" }, h("z-dropdown-input", { key: '77c7347f205565de605e390212640e4b898390e9', value: filterZerva?.bookingStatus, options: Object.entries(EnumBookingStatus).map(([key, value]) => ({ label: t(`booking_status.${value.toLowerCase()}`), value: key })), onValueChange: event => this.handleChange('bookingStatus', event.detail), placeholder: t('chat_filter.booking_status'), class: "mb-2", enableSearch: false, showClearButton: true, disabled: isOnlyCustomers })), h("div", { key: '2549d01cfa6ca777b457b6b143cd5b7db88be337', class: "flex-1" }, h("z-dropdown-input", { key: '2888ec85e99ad7e8c7584f01a8cb3efa0fd0600c', value: filterZerva?.paymentStatus, options: Object.entries(EnumPaymentStatus).map(([key, value]) => ({ label: t(`payment_status.${value.toLowerCase()}`), value: key })), onValueChange: event => this.handleChange('paymentStatus', event.detail), placeholder: t('chat_filter.payment_status'), class: "mb-2", enableSearch: false, showClearButton: true, disabled: isOnlyCustomers })))))))));
    }
    static get is() { return "search-filter-zerva"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["search-filter-zerva.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["search-filter-zerva.css"]
        };
    }
    static get properties() {
        return {
            "filter": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "NonNullable<SearchChatsParams['zerva']>",
                    "resolved": "{ isOnlyCustomers?: boolean; businessId?: string; shopId?: string; bookingNo?: string; name?: string; phoneNumber?: string; email?: string; bookingStartDate?: string; bookingEndDate?: string; paymentStatus?: string; bookingStatus?: string; branchIds?: string[]; serviceIds?: string[]; subIds?: string[]; }",
                    "references": {
                        "NonNullable": {
                            "location": "global",
                            "id": "global::NonNullable"
                        },
                        "SearchChatsParams": {
                            "location": "import",
                            "path": "../../api/type",
                            "id": "src/api/type.ts::SearchChatsParams",
                            "referenceLocation": "SearchChatsParams"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "shopList": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "OptionValue[]",
                    "resolved": "OptionValue[]",
                    "references": {
                        "OptionValue": {
                            "location": "import",
                            "path": "../../components",
                            "id": "src/components.d.ts::OptionValue",
                            "referenceLocation": "OptionValue"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            }
        };
    }
    static get states() {
        return {
            "isShowAdvanced": {},
            "zervaProfile": {},
            "branches": {},
            "serviceSettings": {}
        };
    }
    static get events() {
        return [{
                "method": "filterChange",
                "name": "filterChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "NonNullable<SearchChatsParams['zerva']>",
                    "resolved": "{ isOnlyCustomers?: boolean; businessId?: string; shopId?: string; bookingNo?: string; name?: string; phoneNumber?: string; email?: string; bookingStartDate?: string; bookingEndDate?: string; paymentStatus?: string; bookingStatus?: string; branchIds?: string[]; serviceIds?: string[]; subIds?: string[]; }",
                    "references": {
                        "NonNullable": {
                            "location": "global",
                            "id": "global::NonNullable"
                        },
                        "SearchChatsParams": {
                            "location": "import",
                            "path": "../../api/type",
                            "id": "src/api/type.ts::SearchChatsParams",
                            "referenceLocation": "SearchChatsParams"
                        }
                    }
                }
            }];
    }
}
