import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import useLocalStorage from "./hooks/useLocalStorage";

function App() {
	// Hook to manage language state in local storage
	const [language] = useLocalStorage("language", "eng");
	const [isLoggedIn] = useLocalStorage("isLoggedIn", false);
	const { i18n } = useTranslation();
	const navigate = useNavigate();
	const location = useLocation();

	useEffect(() => {
		// Load language from local storage
		i18n.changeLanguage(language);
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [language]);

	// Here was a problem with detecting updates of isLoggedIn state. Solution was to manually trigger events on storage change when storage was updated.
	// Refer to useLocalStorage hook in ./hooks/useLocalStorage.ts at line 39 for more details
	useEffect(() => {
		// Redirections based on login state
		if (!isLoggedIn) {
			console.log("NOT LOGGED IN");
			navigate("/login");
		}
		if (isLoggedIn && location.pathname === "/login") {
			console.log("LOGGED IN");
			navigate("/orders");
		} else {
			console.log(`ALREADY ${!isLoggedIn ? "NOT " : ""}LOGGED IN`);
		}
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isLoggedIn, navigate]);

	// Conditional rendering based on base path
	return <Outlet />;
}

export default App;
