/**
 * External dependencies.
 */
import { useEffect, useState } from '@wordpress/element';
import {
	Sidebar as ForceUISidebar,
	Menu,
} from '@bsf/force-ui';
import { Link, useLocation, useSearchParams } from 'react-router';

/**
 * Render the sidebar for ths Global Styles page.
 *
 * @since x.x.x
 *
 * @param {Object} props - The element props. 
 * @return {Element}     - The rendered sidebar.
 */
const Sidebar = ( props ) => {
	// Get the navigation prop, and use Search Params.
	const { navigation } = props;
	const [ searchParams ] = useSearchParams();

	// Create a query based on the location, and get the active settings page and the item inside it as well.
	const query = new URLSearchParams( useLocation()?.search );
	const activeSettings = query.get( 'settings' ) || '';
	const activeSettingsNavigationTab = activeSettings || 'colors';

	/**
	 * Internal component to get the link object based on the slug.
	 *
	 * @since x.x.x
	 *
	 * @param {string} slug - The slug of the menu item.
	 * @return {Object}     - An object with the pathname and the search query.
	 */
	const getLinkObject = ( slug ) => {
		const newParams = new URLSearchParams( searchParams.toString() );
		newParams.set( 'settings', slug );
		return {
			pathname: window.location.pathname,
			search: `?${ newParams.toString() }`,
		};
	};

	// State to check if this is a mobile device.
	const [ isMobile, setIsMobile ] = useState( window.innerWidth < 1024 );

	// One-time effect to create a listener for the window resize.
	useEffect( () => {
		const handleResize = () => {
			setIsMobile( window.innerWidth < 1024 );
		};

		window.addEventListener( 'resize', handleResize );

		return () => {
			window.removeEventListener( 'resize', handleResize );
		};
	}, [] );

	// Render the required sidebar.
	return (
		<div className="h-full">
			<ForceUISidebar borderOn className="lg:w-64 uagb-settings-sidebar">
				<ForceUISidebar.Body>
					<ForceUISidebar.Item>
						<Menu className="w-full p-0 gap-4" size="md">
							{ navigation.map( ( menuList ) => (
								<Menu.List key={ menuList.name } heading={ isMobile ? '' : menuList.name } open>
									{ menuList.children.map( ( item ) => (
										<Link
											to={ getLinkObject( item.slug ) }
											key={ item.name }
											className="no-underline"
										>
											<Menu.Item active={ activeSettingsNavigationTab === item.slug }>
												{ item.icon }
												<div className="lg:block hidden">{ item.name }</div>
											</Menu.Item>
										</Link>
									) ) }
								</Menu.List>
							) ) }
						</Menu>
					</ForceUISidebar.Item>
				</ForceUISidebar.Body>
			</ForceUISidebar>
		</div>
	);
};

// Export the Sidebar by default.
export default Sidebar;
