import {forwardRef, useImperativeHandle, useState} from "@wordpress/element";
import useSettings from "../../../../state";
import NavListItem from "./item";

function NavList(props, ref) {
    useImperativeHandle(ref, () => ({
        /**
         * Filter nav menu items by searched value
         *
         * @param {string} value Searched value
         */
        filterItems(value) {
            if (!value || typeof value !== 'string') {
                setFilteredNavItems(navItems);
                return;
            }
            value = value.toLowerCase();
            const filtered = [];
            for (const navItem of navItems) {
                if ('children' in navItem) {
                    // Find an item in children
                    if (navItem.children.length) {
                        const filteredChildren = navItem.children.filter(navItem => navItem.label.toLowerCase().indexOf(value) !== -1);
                        if (filteredChildren.length) {
                            // If at least one item is found in it, then save it
                            filtered.push({
                                ...navItem,
                                children: filteredChildren,
                            });
                        }
                    }
                } else {
                    // Find an item in main list
                    if (navItem.label.toLowerCase().indexOf(value) !== -1) {
                        filtered.push(navItem);
                    }
                }
            }
            setFilteredNavItems(filtered);
        },
    }));

    const {navItems} = useSettings();
    const [filteredNavItems, setFilteredNavItems] = useState(navItems);

    return (
        <div className='lbaic-settings-nav-list'>
            <div className='lbaic-settings-nav-list-in'>
                {!!filteredNavItems?.length && filteredNavItems.map(item => <NavListItem data={item} key={item.slug}/>)}
            </div>
        </div>
    )
}

export default forwardRef(NavList);