import React, { useEffect, useState } from 'react';
import ShowSideBarIcon from '../assets/icon-v3/show-sidebar';
import { MENU_ACTIVE_COLORS, MENU_CODE, SIDEBAR_TYPE, THEME_CODE, themes } from '../constant';
import { enablePer } from '../helper';
import useSaveMenuConfig from '../hooks/use-save-menu-config';
import NavItem from './nav-item';
import OtherMenu from './other-menu';
import PHXSetSettingSite from '../../Func/setting-site/set-setting-site';
import PHXGetSettingSite from '../../Func/setting-site/get-setting-site';
import { classNames } from '../../types';
export default function SideBarDesktop({ currentMenuCode, dataInitMain, isActivityHistory, isSettings, navigation, onChangeSideBarType, setShowSubMenu, showSubMenu, sideBarType, userId, }) {
    const keyPinnedMenu = `menu_pinned_${userId}`;
    const keySavedTheme = `saved_theme_${userId}`;
    const [menu, setMenu] = useState({
        pined: [],
        noPined: [],
    });
    const { getSavedMenuConfig, handleSaveMenuConfig } = useSaveMenuConfig();
    const [totalItem, setTotalItem] = useState(0);
    const [showOtherMenu, setShowOtherMenu] = useState(false);
    const [isChange, setIsChange] = useState(false);
    const [delayHover, setDelayHover] = useState(false);
    const isIconOnly = sideBarType === SIDEBAR_TYPE.ONLY_ICON;
    const isIconWithLabelHorizontal = sideBarType === SIDEBAR_TYPE.ICON_AND_LABEL_HORIZONTAL;
    const isIconWithLabelVertical = sideBarType === SIDEBAR_TYPE.ICON_AND_LABEL_VERTICAL;
    const [loading, setLoading] = useState(true);
    const [theme, setTheme] = useState();
    let visibleMenus = menu.pined.slice(0, totalItem);
    const isActiveMenuVisible = visibleMenus.some((item) => item.code === currentMenuCode);
    // Nếu active menu chưa được hiển thị ra ngoài thì luôn đưa nó xuống cuối
    if (!isActiveMenuVisible) {
        const activeMenu = [...menu.pined, ...menu.noPined].find((item) => item.code === currentMenuCode && isHavePerNavByCode(item.code));
        visibleMenus = menu.pined.slice(0, totalItem - 1);
        if (activeMenu && activeMenu.code !== MENU_CODE.DASHBOARD) {
            visibleMenus.push(activeMenu);
        }
    }
    const removeDuplicateMenu = (arr) => {
        if (!arr)
            return [];
        const seen = new Set();
        return arr.filter((item) => {
            if (seen.has(item.code))
                return false;
            seen.add(item.code);
            return true;
        });
    };
    const savePinedMenu = async (data) => {
        const { pined: pinedMenu } = data;
        await handleSaveMenuConfig({
            key: keyPinnedMenu,
            data: {
                pinedMenu,
            },
        });
    };
    const handleChangePined = (selectedNav) => {
        const { noPined: currNoPined, pined: currPined } = menu;
        let nextPined, nextNoPined;
        if (selectedNav.isPined) {
            nextPined = currPined.filter((nav) => nav.code !== selectedNav.code);
            nextNoPined = [{ ...selectedNav, isPined: false }, ...currNoPined];
        }
        else {
            nextPined = [{ ...selectedNav, isPined: true }, ...currPined];
            nextNoPined = currNoPined.filter((nav) => nav.code !== selectedNav.code);
        }
        setMenu({
            pined: nextPined,
            noPined: nextNoPined,
        });
        setIsChange(!isChange);
    };
    const onOrder = (newArray) => {
        const orderMap = newArray.map((item) => item.code);
        const sortedPined = [...menu.pined].sort((a, b) => {
            const indexA = orderMap.indexOf(a.code);
            const indexB = orderMap.indexOf(b.code);
            // Nếu không tìm thấy trong mảng 1 => để xuống cuối
            if (indexA === -1 && indexB === -1)
                return 0;
            if (indexA === -1)
                return 1;
            if (indexB === -1)
                return -1;
            return indexA - indexB;
        });
        const newMenu = {
            noPined: menu.noPined,
            pined: sortedPined,
        };
        setMenu(newMenu);
        setIsChange(!isChange);
    };
    function isHavePerNavByCode(code) {
        return dataInitMain.perCode.includes(code);
    }
    async function getSavedPinedMenu() {
        try {
            const { pinedMenu } = await getSavedMenuConfig({ key: keyPinnedMenu });
            return pinedMenu || [];
        }
        catch (e) {
            console.error(e);
            return null;
        }
    }
    async function getValidSavePinedMenu() {
        try {
            const pinedSavedArr = await getSavedPinedMenu();
            // lấy những menu được lưu và menu đó phải được phân quyền cho user hiện tại
            const validPined = (pinedSavedArr || []).filter((item) => isHavePerNavByCode(item.code));
            return validPined || [];
        }
        catch (e) {
            console.error(e);
            return [];
        }
    }
    async function getInitPined() {
        const validPinedSaveArr = await getValidSavePinedMenu();
        const currMenu = navigation.find((item) => item.code === currentMenuCode && isHavePerNavByCode(item.code));
        const pined = [];
        const noPined = [];
        if (validPinedSaveArr.length > 0) {
            validPinedSaveArr.forEach((pinedSave) => {
                const found = navigation.find((item) => item.code === pinedSave.code);
                if (found && found.code) {
                    pined.push({ ...found, isPined: true });
                }
            });
            const rest = navigation
                .filter((nav) => !pined.some((item) => item.code === nav.code) && nav.code !== MENU_CODE.SETTING_SITE)
                .map((item) => ({
                ...item,
                disabled: !isHavePerNavByCode(item.code),
            }));
            noPined.push(...rest);
        }
        else {
            navigation.forEach((nav) => {
                if (nav.code === (currMenu === null || currMenu === void 0 ? void 0 : currMenu.code) || nav.code === MENU_CODE.SETTING_SITE) {
                    return;
                }
                const isHavePer = isHavePerNavByCode(nav.code);
                if (isHavePer) {
                    pined.push({
                        ...nav,
                        isPined: true,
                        disabled: !isHavePer,
                    });
                }
                else {
                    noPined.push({
                        ...nav,
                        disabled: !isHavePer,
                    });
                }
            });
            if (currMenu) {
                pined.unshift({ ...currMenu, isPined: true });
            }
            savePinedMenu({
                pined,
                noPined,
            });
        }
        setMenu({
            pined,
            noPined,
        });
    }
    const caculateVisibleMenu = () => {
        var _a;
        let itemHeight = 60;
        if (isIconWithLabelHorizontal || isIconOnly) {
            itemHeight = 42;
        }
        const windowHeight = ((_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.height) || 0 - 66; // 66 là các phần margin và padding của sidebar
        const nextTotalItem = Math.ceil(windowHeight / itemHeight) - (showSubMenu ? 5 : 6); // 6,7 là số item hiện tại đã auto hiển thị
        if (nextTotalItem !== totalItem) {
            setTotalItem(nextTotalItem);
        }
    };
    const onChangeTheme = async (selectedTheme) => {
        try {
            await PHXSetSettingSite({
                key: keySavedTheme,
                data: {
                    theme: selectedTheme.code,
                },
            });
            localStorage.setItem(keySavedTheme, JSON.stringify(selectedTheme));
            setTheme(selectedTheme);
        }
        catch (e) {
            console.error(e);
        }
    };
    useEffect(() => {
        if (!dataInitMain.perCode || navigation.length === 0 || !userId)
            return;
        getInitPined();
    }, [dataInitMain.perCode, navigation.length]);
    useEffect(() => {
        var _a;
        // Log ngay khi component mount
        caculateVisibleMenu();
        (_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.addEventListener('resize', caculateVisibleMenu);
        return () => {
            var _a;
            (_a = window.visualViewport) === null || _a === void 0 ? void 0 : _a.removeEventListener('resize', caculateVisibleMenu);
        };
    }, [showSubMenu]);
    useEffect(() => {
        caculateVisibleMenu();
    }, [sideBarType]);
    useEffect(() => {
        if (menu.pined.length === 0)
            return;
        const timerId = setTimeout(() => {
            savePinedMenu(menu);
        }, 500);
        return () => clearTimeout(timerId);
    }, [isChange]);
    useEffect(() => {
        if (!showSubMenu)
            return; // chỉ chạy khi showSubMenu = true
        setDelayHover(true); // khóa hover
        const timerId = setTimeout(() => {
            setDelayHover(false);
        }, 1000);
        return () => {
            clearTimeout(timerId);
        };
    }, [showSubMenu]);
    useEffect(() => {
        const getTheme = async () => {
            try {
                const themeSetting = await PHXGetSettingSite({
                    key: keySavedTheme,
                });
                const defaultThemeCode = isIconWithLabelHorizontal ? THEME_CODE.PINK : THEME_CODE.BLACK;
                const defaultTheme = themes.find((currTheme) => currTheme.code === defaultThemeCode);
                const savedTheme = themes.find((i) => i.code === (themeSetting === null || themeSetting === void 0 ? void 0 : themeSetting.theme)) || defaultTheme;
                localStorage.setItem(keySavedTheme, JSON.stringify(savedTheme));
                setTheme(savedTheme);
            }
            catch (e) {
                console.error(e);
            }
            finally {
                setLoading(false);
            }
        };
        getTheme();
    }, []);
    useEffect(() => {
        if (navigation.length === 0 || menu.pined.length === 0)
            return;
        setMenu((prev) => {
            const syncCounts = (items, source) => items.map((item) => {
                var _a;
                const fresh = source.find((n) => n.code === item.code);
                if (!fresh)
                    return item;
                return {
                    ...item,
                    requiredActionCount: fresh.requiredActionCount,
                    child: (_a = fresh.child) !== null && _a !== void 0 ? _a : item.child,
                };
            });
            return {
                pined: syncCounts(prev.pined, navigation),
                noPined: syncCounts(prev.noPined, navigation),
            };
        });
    }, [navigation]);
    return (React.createElement(React.Fragment, null, loading ? (React.createElement("div", { "aria-hidden": true, className: classNames('relative z-[40] hidden flex-col items-center lg:inset-y-0 lg:flex', showSubMenu ? 'pt-3' : 'rounded-xl pt-[3.2rem]', isIconOnly ? 'w-[3.25rem]' : '', isIconWithLabelHorizontal ? 'w-[12.5rem]' : '', isIconWithLabelHorizontal && showSubMenu ? 'rounded-l-xl' : '', isIconWithLabelVertical ? 'w-14' : '') })) : (React.createElement("div", { "aria-hidden": true, className: classNames('relative z-[40] hidden w-14 flex-col items-center lg:inset-y-0 lg:flex', showSubMenu ? 'pt-3' : 'rounded-xl pt-[3.2rem]', isIconOnly ? 'w-[3.25rem]' : '', isIconWithLabelHorizontal ? 'w-[10.4rem] transition-all duration-150' : '', isIconWithLabelHorizontal && showSubMenu ? 'rounded-l-xl' : 'rounded-xl'), style: {
            background: !isIconWithLabelHorizontal
                ? `linear-gradient(to bottom, ${theme === null || theme === void 0 ? void 0 : theme.bgColorFrom} -6.91%, ${theme === null || theme === void 0 ? void 0 : theme.bgColorTo} 99.96%)`
                : '',
        } },
        React.createElement("button", { className: classNames('group absolute top-4 mb-4 flex items-center gap-x-2.5 px-3 pb-4 ', showSubMenu ? 'hidden' : '', isIconWithLabelHorizontal
                ? 'ml-1.5 w-full text-gray-700 hover:text-gray-900'
                : `${theme === null || theme === void 0 ? void 0 : theme.sideBarColorDefault} hover:text-white`), onClick: () => setShowSubMenu(true), type: 'button' },
            isIconWithLabelHorizontal && (React.createElement("div", { className: 'absolute left-0 right-0 h-[1.75rem] rounded-lg bg-white opacity-0 transition-opacity group-hover:opacity-100' })),
            React.createElement("div", { className: classNames('absolute bottom-0   h-[0.5px]', isIconWithLabelHorizontal ? 'left-2 right-3 bg-[#CCCCCC]' : 'left-3 right-3 bg-white opacity-40') }),
            React.createElement(ShowSideBarIcon, null),
            isIconWithLabelHorizontal && (React.createElement("p", { className: 'absolute -top-[0.2rem] left-[2.25rem] text-xxs' }, "M\u1EDF thanh b\u00EAn"))),
        React.createElement("div", null, removeDuplicateMenu(visibleMenus).map((item, index) => {
            const isActive = !!(item === null || item === void 0 ? void 0 : item.current);
            return (React.createElement(React.Fragment, { key: item.code }, enablePer(item.code, dataInitMain.perCode) && (React.createElement(NavItem, { bgActiveColor: MENU_ACTIVE_COLORS[index % MENU_ACTIVE_COLORS.length], child: item.child, code: item.code, delayHover: delayHover, href: item.path, isActive: isActive, isShowOtherMenu: showOtherMenu, name: item.name, parentPath: item.path, perCodes: dataInitMain.perCode, requiredActionCount: item.requiredActionCount, showSubMenu: showSubMenu && currentMenuCode === item.code, sideBarType: sideBarType, theme: theme }))));
        })),
        React.createElement(OtherMenu, { active: showOtherMenu, handleChangePined: handleChangePined, noPined: menu.noPined, onChangeSideBarType: onChangeSideBarType, onChangeTheme: onChangeTheme, onOrder: onOrder, pined: menu.pined, setActive: setShowOtherMenu, sideBarType: sideBarType, theme: theme }),
        visibleMenus.length > 0 && (React.createElement("div", { className: classNames('absolute  flex flex-col items-center', isIconWithLabelHorizontal ? 'bottom-1' : 'bottom-0') },
            React.createElement(NavItem, { key: 'activity_history_nav', bgActiveColor: MENU_ACTIVE_COLORS[1], code: 'ACTIVITY_HISTORY', href: '/activity-history/list', isActive: isActivityHistory, name: 'L\u1ECBch s\u1EED ho\u1EA1t \u0111\u1ED9ng', sideBarType: sideBarType, theme: theme }),
            React.createElement(NavItem, { key: 'setting_nav', bgActiveColor: MENU_ACTIVE_COLORS[2], code: MENU_CODE.SETTING_SITE, href: '/setting', isActive: isSettings, name: 'C\u00E0i \u0111\u1EB7t', sideBarType: sideBarType, theme: theme })))))));
}
//# sourceMappingURL=side-bar.js.map