import { Host, h } from "@stencil/core";
import { Icon } from "../internal-component/icon";
import { useTranslation } from "../../utils/utils";
import { ZButton } from "../internal-component/z-button";
import { ZIconButton } from "../internal-component/z-icon-button";
import { customFiltersStore, filterChatsStore, platformConnectionsStore, chatsStore } from "../../store/store";
import { resetChatFilter } from "../../store/chat";
import { getCustomerIds, getNewReservationSummaryCustomerIds } from "../../api/platform";
export class SearchBox {
    query = '';
    showDialog = false;
    showCustomFilterDialog = false;
    showDialogSearchChatUser = false;
    isUnRead = false;
    isGroup = false;
    filterSet;
    filterType = 'quick';
    selectedFilter = null;
    internalUnreadLoading = false;
    internalGroupLoading = false;
    internalResetLoading = false;
    internalAdvancedLoading = false;
    internalCustomFilterLoading = false;
    disposeStore;
    componentDidLoad() {
        document.addEventListener('keydown', this.handleKeyDown);
        this.disposeStore = chatsStore.onChange('loading', loading => {
            if (!loading) {
                this.internalUnreadLoading = false;
                this.internalGroupLoading = false;
                this.internalResetLoading = false;
                this.internalAdvancedLoading = false;
                this.internalCustomFilterLoading = false;
            }
        });
    }
    disconnectedCallback() {
        document.removeEventListener('keydown', this.handleKeyDown);
        if (this.disposeStore)
            this.disposeStore();
    }
    handleKeyDown = (e) => {
        if (e.key === 'Escape') {
            this.showDialog = false;
            this.showCustomFilterDialog = false;
        }
    };
    handleInput = (e) => {
        const value = e.target.value;
        this.query = value;
    };
    handleEnter = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            this.showDialogSearchChatUser = true;
            setTimeout(() => {
                this.query = '';
            }, 200);
        }
    };
    handleClick = () => {
        this.showDialogSearchChatUser = true;
        setTimeout(() => {
            this.query = '';
        }, 200);
    };
    handleToggleUnread = () => {
        this.internalUnreadLoading = true;
        this.isUnRead = !this.isUnRead;
        const _read = this.isUnRead ? false : null;
        filterChatsStore.set('filterChat', {
            ...filterChatsStore.get('filterChat'),
            read: _read,
        });
    };
    handleToggleGroup = () => {
        this.internalGroupLoading = true;
        this.isGroup = !this.isGroup;
        const _type = this.isGroup ? 'group' : undefined;
        filterChatsStore.set('filterChat', {
            ...filterChatsStore.get('filterChat'),
            type: _type,
        });
    };
    handleResetFilters = () => {
        this.internalResetLoading = true;
        // Reset all filter states
        this.isUnRead = false;
        this.isGroup = false;
        this.query = '';
        // Clear filter store
        resetChatFilter();
        // Clear filter set
        this.filterSet = undefined;
    };
    getZrmzCustomerIds = async (filter) => {
        const customerIds = new Set();
        if (!filter)
            return customerIds;
        if (filter.isOnlyCustomers) {
            const fetchCustomerIds = new Map();
            const _connections = platformConnectionsStore.get('connections');
            for (const con in _connections) {
                if (_connections[con].zrmz) {
                    const businessId = _connections[con].zrmz.business_profile_id;
                    const shopId = _connections[con].zrmz.shop_profile_setting_id;
                    fetchCustomerIds.set(`${businessId}:${shopId}`, { businessId, shopId });
                }
            }
            await Promise.all(Array.from(fetchCustomerIds.values()).map(async ({ businessId }) => {
                const { ids } = await getCustomerIds({
                    business_profile_id: businessId,
                    offset: 0,
                    limit: 999999,
                });
                if (ids) {
                    ids.forEach(id => id && id !== 'undefined' && customerIds.add(id));
                }
            }));
        }
        else if (filter.businessId && filter.shopId) {
            const { ids } = await getCustomerIds({
                business_profile_id: filter.businessId,
                shop_id: filter.shopId,
                name: filter.name,
                ...(filter.phoneNumber && {
                    phone_number: filter.phoneNumber,
                    phone_number_country_code: '66',
                }),
                email: filter.email,
                point_received_type: filter.totalPointType,
                point_received_min: filter.totalPointMin,
                point_received_max: filter.totalPointMax,
                point_type: filter.remainingPointType,
                point_min: filter.remainingPointMin,
                point_max: filter.remainingPointMax,
                gender: filter.gender === 'all' ? undefined : filter.gender,
                channel: filter.channel === 'all' ? undefined : filter.channel,
                channel_status: filter.channelStatus === 'all' ? undefined : filter.channelStatus,
                channel_user: filter.channelUser,
                birthdate_start: filter.birthdateStart,
                birthdate_end: filter.birthdateEnd,
                ...Object.entries(filter.customFields || {}).reduce((acc, [key, value]) => {
                    if (value !== null && value !== undefined && String(value) !== '') {
                        acc[key] = String(value);
                        acc[`custom_${key}`] = String(value);
                    }
                    return acc;
                }, {}),
                offset: 0,
                limit: 999999,
            });
            if (ids) {
                ids.forEach(id => id && id !== 'undefined' && customerIds.add(id));
            }
        }
        return customerIds;
    };
    handleFilter = async (filter) => {
        const _search = filter.search ? filter.search.trim() : '';
        const customerIds = new Set();
        const zrmzCustomerIds = new Set();
        if (filter.zerva) {
            if (filter.zerva.isOnlyCustomers) {
                const fetchCustomerIds = new Map();
                const _connections = platformConnectionsStore.get('connections');
                for (const con in _connections) {
                    if (_connections[con].zerva) {
                        const businessId = _connections[con].zerva.business_profile_id;
                        const shopId = _connections[con].zerva.shop_profile_setting_id;
                        fetchCustomerIds.set(`${businessId}:${shopId}`, { businessId, shopId });
                    }
                }
                await Promise.all(Array.from(fetchCustomerIds.values()).map(async ({ businessId, shopId }) => {
                    const { result: { customer_ids } } = await getNewReservationSummaryCustomerIds({
                        business_profile_id: businessId,
                        shop_profile_setting_id: shopId,
                    });
                    if (customer_ids) {
                        customer_ids.forEach(id => id && id !== 'undefined' && customerIds.add(id));
                    }
                }));
            }
            else if (filter.zerva.businessId && filter.zerva.shopId) {
                const { result: { customer_ids } } = await getNewReservationSummaryCustomerIds({
                    business_profile_id: filter.zerva?.businessId,
                    shop_profile_setting_id: filter.zerva?.shopId,
                    booking_no: filter.zerva?.bookingNo,
                    customer_name: filter.zerva?.name,
                    customer_tel: filter.zerva?.phoneNumber,
                    customer_email: filter.zerva?.email,
                    booking_start_date: filter.zerva?.bookingStartDate,
                    booking_end_date: filter.zerva?.bookingEndDate,
                    payment_status: filter.zerva?.paymentStatus,
                    booking_status: filter.zerva?.bookingStatus,
                    branch_ids: filter.zerva?.branchIds?.length > 0 ? filter.zerva.branchIds.join(',') : undefined,
                    sub_ids: filter.zerva?.subIds?.length > 0 ? filter.zerva.subIds.join(',') : undefined,
                });
                if (customer_ids) {
                    customer_ids.forEach(id => id && id !== 'undefined' && customerIds.add(id));
                }
            }
        }
        if (filter.zrmz) {
            const ids = await this.getZrmzCustomerIds(filter.zrmz);
            ids.forEach(id => zrmzCustomerIds.add(id));
        }
        const transformFilters = {
            ...filterChatsStore.get('filterChat'),
            connections: filter.connections,
            lastAnswerByIds: ((filter.lastAnswerByIds || []).length || 0) > 0 ? filter.lastAnswerByIds : undefined,
            statusIds: ((filter.statusIds || []).length || 0) > 0 ? filter.statusIds : undefined,
            tagIds: ((filter.tagIds || []).length || 0) > 0 ? filter.tagIds : undefined,
            search: _search.length > 0 ? _search : undefined,
            read: filter.read,
            type: filter.type,
            verifySlip: filter.verifySlip,
            verifySlipValue: filter.verifySlipValue,
            userIds: Array.from(customerIds),
            zrmzCustomerIds: Array.from(zrmzCustomerIds),
        };
        filterChatsStore.set('filterChat', transformFilters);
        if (filter.read !== undefined) {
            this.isUnRead = filter.read;
        }
        this.filterSet = filter;
        this.showDialog = false;
    };
    handleOpenAdvancedFilter = () => {
        this.filterType = 'advanced';
        this.showDialog = true;
    };
    handleOpenCustomFilterDialog = () => {
        this.showCustomFilterDialog = true;
    };
    handleCloseCustomFilterDialog = () => {
        this.showCustomFilterDialog = false;
    };
    handleCloseDialog = () => {
        this.showDialog = false;
        this.showCustomFilterDialog = false;
    };
    handleCloseDialogSearchChatUser = () => {
        this.showDialogSearchChatUser = false;
    };
    handleCustomFilterSelect = () => {
        this.internalCustomFilterLoading = true;
    };
    handleCustomFilterBackdropClick = (e) => {
        if (e.target === e.currentTarget) {
            this.showCustomFilterDialog = false;
        }
    };
    handleDialogBackdropClick = (e) => {
        if (e.target === e.currentTarget) {
            this.showDialog = false;
        }
    };
    handleSearchChatUserBackdropClick = (e) => {
        if (e.target === e.currentTarget) {
            this.showDialogSearchChatUser = false;
        }
    };
    handleInitCustomFilter = () => {
        this.filterType = 'advanced';
        this.selectedFilter = null;
        this.showDialog = true;
    };
    handleAddCustomFilter = () => {
        this.filterType = 'custom';
        this.selectedFilter = null;
        this.showDialog = true;
    };
    handleEditCustomFilter = (event) => {
        this.selectedFilter = event.detail;
        this.filterType = 'custom';
        this.showDialog = true;
    };
    handleSearchSubmit = (event) => {
        this.internalAdvancedLoading = true;
        this.handleFilter(event.detail);
        this.showCustomFilterDialog = false;
    };
    renderQuickFilter() {
        const t = useTranslation();
        const filterConfig = filterChatsStore.get('filterConfig');
        return (h("div", { class: "mt-2 flex gap-2" }, h("div", { class: "search-box-quick-filter-wrapper scroll-container flex-1" }, h("div", { class: "flex gap-2" }, h("div", null, h(ZButton, { size: "small", padding: "px-4 py-1.5", variant: this.isUnRead ? 'primary' : 'outlined', disabled: chatsStore.get('loading') && this.internalUnreadLoading, startIcon: this.internalUnreadLoading && chatsStore.get('loading') ? (h(Icon, { name: "LoaderCircle", addClass: "size-4 animate-spin" })) : (h(Icon, { name: 'MailWarning', addClass: "size-4" })), label: this.isUnRead ? t('unread') : undefined, title: t('unread'), onClick: this.handleToggleUnread })), h("div", { id: "search-chat-channel" }, h("menu-chat-channel", { referenceSelector: "search-chat-channel" })), filterConfig && filterConfig.config && filterConfig.config.isShowFilterType === true && (h("div", null, h(ZButton, { size: "small", padding: "px-4 py-1.5", variant: this.isGroup ? 'primary' : 'outlined', disabled: chatsStore.get('loading') && this.internalGroupLoading, startIcon: this.internalGroupLoading && chatsStore.get('loading') ? (h(Icon, { name: "LoaderCircle", addClass: "size-4 animate-spin" })) : (h(Icon, { name: 'UsersRound', addClass: "size-4" })), label: this.isGroup ? t('chat_filter.group') : undefined, title: t('chat_filter.group'), onClick: this.handleToggleGroup }))))), h("div", null, h(ZButton, { size: "small", variant: this.internalResetLoading ? 'text' : 'text-underline', disabled: chatsStore.get('loading') && this.internalResetLoading, startIcon: this.internalResetLoading && chatsStore.get('loading') ? h(Icon, { name: "LoaderCircle", addClass: "size-4 animate-spin" }) : undefined, label: this.internalResetLoading ? '' : t('chat_filter.reset'), onClick: this.handleResetFilters }))));
    }
    renderAdvancedFilter() {
        const t = useTranslation();
        return (h("div", { class: "mt-2 flex gap-2" }, h("div", { class: "search-box-quick-filter-wrapper scroll-container flex-1" }, h("div", { class: "flex gap-2" }, h(ZButton, { size: "small", padding: "px-4 py-1.5", variant: "primary", startIcon: h(Icon, { name: 'Search', addClass: "size-4" }), label: t('chat_filter.search_result'), title: t('chat_filter.search_result'), onClick: this.handleOpenAdvancedFilter }))), h("div", null, h(ZButton, { size: "small", variant: this.internalResetLoading ? 'text' : 'text-underline', disabled: chatsStore.get('loading') && this.internalResetLoading, startIcon: this.internalResetLoading && chatsStore.get('loading') ? h(Icon, { name: "LoaderCircle", addClass: "size-4 animate-spin" }) : undefined, label: this.internalResetLoading ? '' : t('chat_filter.reset'), onClick: this.handleResetFilters }))));
    }
    renderCustomFilter() {
        const t = useTranslation();
        const selectedFilter = customFiltersStore.get('selectedFilter');
        const selectedFilterName = selectedFilter ? `${t('chat_filter.filter')}: ${selectedFilter.name}` : '';
        return (h("div", { class: "mt-2 flex gap-2" }, h("div", { class: "search-box-quick-filter-wrapper scroll-container flex-1" }, h("div", { class: "flex gap-2" }, h(ZButton, { size: "small", padding: "px-4 py-1.5", variant: "primary", disabled: chatsStore.get('loading') && this.internalResetLoading, startIcon: this.internalResetLoading && chatsStore.get('loading') ? h(Icon, { name: "LoaderCircle", addClass: "size-4 animate-spin" }) : h(Icon, { name: 'Filter', addClass: "size-4" }), label: selectedFilterName, title: selectedFilterName, onClick: this.handleResetFilters }))), h("div", null, h(ZButton, { size: "small", variant: this.internalResetLoading ? 'text' : 'text-underline', disabled: chatsStore.get('loading') && this.internalResetLoading, startIcon: this.internalResetLoading && chatsStore.get('loading') ? h(Icon, { name: "LoaderCircle", addClass: "size-4 animate-spin" }) : undefined, label: this.internalResetLoading ? '' : t('chat_filter.reset'), onClick: this.handleResetFilters }))));
    }
    renderFilter() {
        const _filterType = filterChatsStore.get('filterType');
        switch (_filterType) {
            case 'quick':
                return this.renderQuickFilter();
            case 'advanced':
                return this.renderAdvancedFilter();
            default:
                return this.renderCustomFilter();
        }
    }
    render() {
        const t = useTranslation();
        return (h(Host, { key: 'd9d9a39b249b6ab7efa2ccd71570dffd8cd01568' }, h("div", { key: 'e186453d6c4ed13baeb721a539b224b0a67f0426', class: "search-box" }, h("div", { key: 'fb6d9785ba6ae0c7ffddd98a4c4412a27fc19e70', class: "flex-1", id: "search-chat-type" }, h("menu-chat-type", { key: 'ce3fd8c7645543e11e17f915a251c279b5bcf3b0', referenceSelector: "search-chat-type" })), h("div", { key: '58e2379cb2658adae7bede87e4e226ff51603100', class: "search-box-input-wrapper" }, h("div", { key: '88c6dfb28de1b7365dddc965a98d0851a03cc10a', class: "search-box-input-box" }, h("input", { key: '72a4ccfde6cad80d4896594dfcf2a3c0fa6c8a97', id: "search", type: "text", placeholder: t('chat_tab.search_chat'), class: "search-box-input", value: this.query, onInput: this.handleInput, onKeyDown: this.handleEnter }), h("div", { key: '86f0cb6b9dc9ff07fea3e5183803d9ba04b3d24a', class: "search-box-input-icon", onClick: this.handleClick }, h(Icon, { key: '4442305bc0da26cb06d9b58d29920064d847a895', name: "Search" }))), h(ZIconButton, { key: '9b0b74f26a3861e7ed0064df2ca253fbbf8094fd', variant: "text", iconName: "Filter", disabled: chatsStore.get('loading') && this.internalCustomFilterLoading, isLoading: this.internalCustomFilterLoading && chatsStore.get('loading'), onClick: this.handleOpenCustomFilterDialog })), this.renderFilter(), this.showCustomFilterDialog && (h("div", { key: 'fa1d9171ecaabf5d61781b7a4e0676cb31648c2d', class: "dialog-backdrop", onClick: this.handleCustomFilterBackdropClick }, h("dialog-custom-filter", { key: '54ce59403ea7e8c0805432210e23837f50df6177', onInitial: this.handleInitCustomFilter, onAdd: this.handleAddCustomFilter, onEdit: this.handleEditCustomFilter, onClose: this.handleCloseCustomFilterDialog, onFilterSelect: this.handleCustomFilterSelect }))), this.showDialog && (h("div", { key: 'c847779fdf968e3f8e0961be055674c8d333b84e', class: "dialog-backdrop", onClick: this.handleDialogBackdropClick }, h("dialog-search", { key: '5fa943398caf38e4445b44fa651256fc05ebf4c2', selectedFilter: this.selectedFilter, filterType: this.filterType, oldFilter: this.filterSet, onCancel: this.handleCloseDialog, onSearch: this.handleSearchSubmit }))), this.showDialogSearchChatUser && (h("div", { key: '232539406523a7b809b2bc28f15b986817f69c91', class: "dialog-backdrop", onClick: this.handleSearchChatUserBackdropClick }, h("dialog-search-chat-user", { key: '1a31797bf1303ef90e336950a07d7de3171f8320', initialQuery: this.query, onClose: this.handleCloseDialogSearchChatUser }))))));
    }
    static get is() { return "search-box"; }
    static get originalStyleUrls() {
        return {
            "$": ["search-box.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["search-box.css"]
        };
    }
    static get states() {
        return {
            "query": {},
            "showDialog": {},
            "showCustomFilterDialog": {},
            "showDialogSearchChatUser": {},
            "isUnRead": {},
            "isGroup": {},
            "filterSet": {},
            "filterType": {},
            "selectedFilter": {},
            "internalUnreadLoading": {},
            "internalGroupLoading": {},
            "internalResetLoading": {},
            "internalAdvancedLoading": {},
            "internalCustomFilterLoading": {}
        };
    }
}
