import { useEffect, useState } from '@wordpress/element';
import { Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import { SettingsProvider, useSettings } from './contexts/SettingsContext';
import { NoticesProvider } from './contexts/NoticesContext';
import HeaderNav from './components/HeaderNav';
import SupportPopup from './components/SupportPopup';
import AppsScriptNotice from './components/AppsScriptNotice';
import UpgradeNotice from './components/UpgradeNotice';
import LicenseNotice from './components/LicenseNotice';
import useAdminMenuSync from './hooks/useAdminMenuSync';
import Dashboard from './pages/Dashboard';
import Settings from './pages/Settings';
import Setup from './pages/Setup';
import { isPro, isUltimateActive } from './Helpers';

const MainLayout = () => {
	const location = useLocation();
	const navigate = useNavigate();
	const { isSetupComplete } = useSettings();
	const [ supportOpen, setSupportOpen ] = useState( false );
	const isSetupRoute = location.pathname === '/setup';

	useAdminMenuSync( location.pathname, navigate );

	useEffect( () => {
		if ( ! isSetupComplete && ! isSetupRoute ) {
			navigate( '/setup', { replace: true } );
		}
	}, [ isSetupComplete, isSetupRoute, navigate ] );

	// Notice placement follows the legacy templates: above the wrapper on the dashboard
	// (dashboard/base.php), inside it on the setup wizard (setup/base.php).
	return (
		<>
			{ ! isSetupRoute && <LicenseNotice /> }
			{ ! isSetupRoute && <UpgradeNotice /> }
			{ ! isSetupRoute && <AppsScriptNotice /> }
			<section className="ssgsw-wrapper">
				{ isSetupRoute && <AppsScriptNotice /> }
				{ ! isSetupRoute && <HeaderNav onOpenSupport={ () => setSupportOpen( true ) } /> }

				<Routes>
					<Route path="/" element={ <Dashboard /> } />
					<Route path="/settings" element={ <Settings /> } />
					<Route path="/setup" element={ <Setup /> } />
					<Route path="*" element={ <Navigate to="/" replace /> } />
				</Routes>

				{ isUltimateActive() && isPro() && (
					<SupportPopup isOpen={ supportOpen } onClose={ () => setSupportOpen( false ) } />
				) }
			</section>
		</>
	);
};

/**
 * Shared providers. The Add-ons and Logs pages have their own menu items, so they render
 * a single page instead of the dashboard/settings/setup routes.
 *
 * @param {Object}      props
 * @param {JSX.Element} props.children Page to render; defaults to the routed dashboard app.
 */
const App = ( { children } ) => (
	<SettingsProvider>
		<NoticesProvider>{ children || <MainLayout /> }</NoticesProvider>
	</SettingsProvider>
);

export default App;
