"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = SearchBarHeaderDesktop;
const tslib_1 = require("tslib");
const react_1 = require("@headlessui/react");
const outline_1 = require("@heroicons/react/24/outline");
const solid_1 = require("@heroicons/react/24/solid");
const image_1 = tslib_1.__importDefault(require("next/image"));
const react_2 = tslib_1.__importStar(require("react"));
const Icon_1 = require("../../assets/Icon");
const constant_1 = require("../../constant");
const helper_1 = require("../../helper");
const use_save_menu_config_1 = tslib_1.__importDefault(require("../../hooks/use-save-menu-config"));
const bold_icon_1 = tslib_1.__importDefault(require("../bold-icon"));
const types_1 = require("../../../types");
const Loading_1 = require("../../../Loading");
const __1 = require("../../../..");
function ListItem({ activeIndex, currentActive, list, onClickItem, title, }) {
    const handleRedirectByEnter = async (item) => {
        onClickItem(item);
        await (0, helper_1.delay)(200);
        window.location.href = item.path;
    };
    (0, react_2.useEffect)(() => {
        if (!currentActive)
            return;
        const handleEnterPress = (e) => {
            if (e.key !== 'Enter')
                return;
            const activeItem = list[activeIndex];
            if (activeItem) {
                handleRedirectByEnter(activeItem);
            }
        };
        window.addEventListener('keydown', handleEnterPress);
        return () => window.removeEventListener('keydown', handleEnterPress);
    }, [activeIndex, currentActive, list.length]);
    return (react_2.default.createElement("div", { className: 'mt-4 px-4' },
        react_2.default.createElement("p", { className: 'mb-1.5 text-xxs font-[450] text-gray-500' }, title),
        react_2.default.createElement("div", null, list.map((item, index) => {
            const isActive = activeIndex === index && currentActive;
            return (react_2.default.createElement("a", { key: item.id, className: (0, types_1.classNames)('group -ml-2 flex items-center gap-x-2 px-2 py-1.5', isActive ? 'rounded-lg bg-gray-50' : 'hover:rounded-lg  hover:bg-gray-50'), href: item.path, onClick: (e) => {
                    e.preventDefault();
                    handleRedirectByEnter(item);
                } },
                react_2.default.createElement(bold_icon_1.default, { code: item.code, index: index }),
                react_2.default.createElement("p", { className: 'text-xs font-[450] text-gray-600 group-hover:text-gray-900' }, item.name)));
        }))));
}
function SearchBarHeaderDesktop({ menu, perCode, sideBarType, userId, hasVerticalScroll, }) {
    const [isShowFixedAction, setIsShowFixAction] = (0, react_2.useState)(false);
    const keyHistory = `global_search_history_${userId}`;
    const { getSavedMenuConfig, handleSaveMenuConfig } = (0, use_save_menu_config_1.default)();
    const [show, setShow] = (0, react_2.useState)(false);
    const [searchValue, setSearchValue] = (0, react_2.useState)('');
    const [result, setResult] = (0, react_2.useState)([]);
    const [flattenMenu, setFlattenMenu] = (0, react_2.useState)([]);
    const [history, setHistory] = (0, react_2.useState)([]);
    const [loading, setLoading] = (0, react_2.useState)(false);
    const [isEmptyResult, setIsEmptyResult] = (0, react_2.useState)(false);
    const [activeIndexByArrowKey, setActiveIndexByArrowKey] = (0, react_2.useState)(-1);
    function onHide() {
        setShow(false);
        setSearchValue('');
        setActiveIndexByArrowKey(-1);
    }
    async function getHistory() {
        try {
            const { listHistory } = await getSavedMenuConfig({ key: keyHistory });
            setHistory(listHistory || []);
            return null;
        }
        catch (e) {
            console.error(e);
            return null;
        }
    }
    const saveHistory = async (data) => {
        await handleSaveMenuConfig({
            key: keyHistory,
            data: { listHistory: data },
        });
    };
    const handleSearch = async () => {
        setLoading(true);
        try {
            if (!searchValue) {
                setResult([]);
                setIsEmptyResult(false);
                return;
            }
            const filteredData = flattenMenu
                .filter((item) => (0, helper_1.normalizeString)(item.name).includes((0, helper_1.normalizeString)(searchValue)) && perCode.includes(item.pathCode))
                .slice(0, 10);
            setResult(filteredData);
            setIsEmptyResult(filteredData.length === 0);
            setActiveIndexByArrowKey(-1);
        }
        catch (e) {
            console.error(e);
        }
        finally {
            setLoading(false);
        }
    };
    const handleSaveHistory = async (item) => {
        // lọc ra phần tử có đã tồn tại và chỉ lưu tối đa 5 phần tử
        const filtereds = history.filter((curr) => curr.id !== item.id);
        saveHistory([item, ...filtereds].slice(0, 5));
        onHide();
    };
    (0, react_2.useEffect)(() => {
        const timerId = setTimeout(() => {
            handleSearch();
        }, 300);
        return () => clearTimeout(timerId);
    }, [searchValue]);
    (0, react_2.useEffect)(() => {
        setFlattenMenu((0, helper_1.flattenMenuTree)(menu));
    }, [menu.length]);
    (0, react_2.useEffect)(() => {
        getHistory();
        const handlerOpenModalSearchByShortcut = (e) => {
            const isMac = navigator.platform.toUpperCase().includes('MAC');
            // Cmd + K (Mac) hoặc Ctrl + K (Win)
            if ((isMac && e.metaKey && e.key === 'k') || (!isMac && e.ctrlKey && e.key === 'k')) {
                e.preventDefault(); // chặn trình duyệt mở search
                setShow(true);
            }
        };
        window.addEventListener('keydown', handlerOpenModalSearchByShortcut);
        return () => window.removeEventListener('keydown', handlerOpenModalSearchByShortcut);
    }, []);
    (0, react_2.useEffect)(() => {
        if (!show)
            return;
        const handleSelectItemByKeyArrow = (e) => {
            const totalItem = history.length + result.length;
            if (!totalItem)
                return;
            if (e.key === 'ArrowDown') {
                setActiveIndexByArrowKey((prev) => {
                    // backup nếu prev bị lệch so với số lượng mới
                    const safePrev = prev >= totalItem ? 0 : prev;
                    return safePrev === totalItem - 1 ? 0 : safePrev + 1;
                });
            }
            if (e.key === 'ArrowUp') {
                setActiveIndexByArrowKey((prev) => {
                    const safePrev = prev >= totalItem ? 0 : prev;
                    return safePrev === 0 ? totalItem - 1 : safePrev - 1;
                });
            }
        };
        window.addEventListener('keydown', handleSelectItemByKeyArrow);
        return () => {
            window.removeEventListener('keydown', handleSelectItemByKeyArrow);
        };
        // không cần phụ thuộc vào activeIndex nữa
    }, [show, history.length, result.length]);
    (0, __1.useMainwrapV4EventBus)(constant_1.FIXED_ACTION_EVENT, (payload) => {
        if (isShowFixedAction !== payload.show) {
            setIsShowFixAction(payload.show || false);
        }
    });
    return (react_2.default.createElement("div", { className: 'absolute left-1/2 hidden -translate-x-1/4 lg:block' },
        react_2.default.createElement("button", { className: (0, types_1.classNames)('flex h-8 w-[18.75rem] items-center overflow-hidden rounded-2xl border border-gray-300 px-2 transition-all duration-200 ease-in-out', sideBarType === constant_1.SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL ? 'bg-[#F7F7F7]' : 'bg-[#EBEBEB]', isShowFixedAction && hasVerticalScroll ? 'pointer-events-none translate-y-4 opacity-0' : ''), onClick: () => setShow(true), type: 'button' },
            react_2.default.createElement(image_1.default, { alt: 'icon', height: 16, quality: 100, src: Icon_1.IconV2.SEARCH, width: 16 }),
            react_2.default.createElement("p", { className: 'ml-0.5 flex-1 border-none text-left text-xxs text-gray-500' }, "G\u00F5 \u0111\u1EC3 truy c\u1EADp nhanh\u2026")),
        react_2.default.createElement(react_1.Transition.Root, { as: react_2.Fragment, show: show },
            react_2.default.createElement(react_1.Dialog, { as: 'div', className: 'relative z-50 hidden lg:block', onClose: onHide, static: true },
                react_2.default.createElement("div", { className: 'fixed inset-0 z-50 overflow-y-auto' },
                    react_2.default.createElement(react_1.Transition.Child, { as: react_2.Fragment, enter: 'transform ease-out duration-300 transition', enterFrom: 'opacity-0 scale-95', enterTo: 'opacity-100 scale-100', leave: 'transition ease-in duration-200', leaveFrom: 'opacity-100 scale-100', leaveTo: 'opacity-0 scale-95' },
                        react_2.default.createElement(react_1.Dialog.Panel, { className: 'mx-auto mt-16  max-h-[calc(100vh-9rem)] max-w-2xl transform overflow-hidden overflow-y-auto rounded-xl bg-white pb-4 outline outline-1 outline-black/5 drop-shadow-2xl' },
                            react_2.default.createElement("div", { className: 'sticky top-0 flex h-[3.25rem] items-center justify-between gap-x-4 border-b border-gray-100  bg-white px-4' },
                                react_2.default.createElement("div", { className: 'flex flex-1 items-center gap-x-2 overflow-hidden' },
                                    loading ? (react_2.default.createElement(Loading_1.PHXSpinner, { className: ' h-[1.125rem] w-[1.125rem] !text-gray-500' })) : (react_2.default.createElement(solid_1.MagnifyingGlassIcon, { "aria-hidden": 'true', className: 'pointer-events-none col-start-1 row-start-1 h-[1.125rem] w-[1.125rem] self-center text-gray-400 dark:text-gray-500' })),
                                    react_2.default.createElement("input", { autoFocus: show, className: 'flex-1 border-none bg-transparent !p-0 text-xs text-gray-900 placeholder:text-gray-400 focus:ring-0', onChange: (e) => setSearchValue(e.target.value), placeholder: 'G\u00F5 \u0111\u1EC3 truy c\u1EADp nhanh\u2026', type: 'text', value: searchValue })),
                                searchValue && (react_2.default.createElement("button", { className: 'flex h-7 w-7 items-center justify-center rounded-lg hover:bg-gray-100', onClick: () => setSearchValue(''), type: 'button' },
                                    react_2.default.createElement(solid_1.XMarkIcon, { className: 'h-[1.125rem] w-[1.125rem] text-gray-600' })))),
                            result.length === 0 ? (react_2.default.createElement(react_2.default.Fragment, null, isEmptyResult ? (react_2.default.createElement("div", { className: 'flex h-[11.25rem] w-full items-center justify-center' },
                                react_2.default.createElement("div", { className: 'flex flex-col items-center text-gray-500' },
                                    react_2.default.createElement(outline_1.FaceFrownIcon, { className: 'mb-4 h-8 w-8' }),
                                    react_2.default.createElement("p", { className: 'mb-2 text-sm font-semibold text-gray-900' }, "Kh\u00F4ng t\u00ECm th\u1EA5y"),
                                    react_2.default.createElement("p", { className: 'line-clamp-2 w-[60ch] truncate text-center text-sm text-gray-500' },
                                        "Kh\u00F4ng c\u00F3 k\u1EBFt qu\u1EA3 cho \u201C",
                                        react_2.default.createElement("span", { className: 'font-medium text-gray-900' }, searchValue),
                                        "\u201D")))) : (react_2.default.createElement("div", { className: 'flex h-[8.75rem] w-full items-center justify-center' },
                                react_2.default.createElement("div", { className: 'flex flex-col items-center gap-y-2 text-gray-500' },
                                    react_2.default.createElement(solid_1.MagnifyingGlassIcon, { "aria-hidden": 'true', className: 'h-8 w-8' }),
                                    react_2.default.createElement("p", { className: 'text-xs' }, "T\u00ECm ki\u1EBFm menu / ch\u1EE9c n\u0103ng...")))))) : (react_2.default.createElement(ListItem, { key: 'result', activeIndex: activeIndexByArrowKey, currentActive: activeIndexByArrowKey < result.length && show, list: result, onClickItem: handleSaveHistory, title: 'K\u1EBFt qu\u1EA3 t\u00ECm ki\u1EBFm' })),
                            history.length > 0 && (react_2.default.createElement(ListItem, { key: 'recently', activeIndex: activeIndexByArrowKey - result.length, currentActive: activeIndexByArrowKey > result.length - 1 && show, list: history, onClickItem: handleSaveHistory, title: 'G\u1EA7n \u0111\u00E2y' })))))))));
}
//# sourceMappingURL=SearchBarDesktop.js.map