import PropTypes from "prop-types";
import {
	BrowserRouter,
	Routes,
	Route,
	Navigate,
	useLocation
} from "react-router-dom";
import {useCheckLogin} from "../hooks";
import Login from "./Login";

const RequiereAuth = ({devURL,redirectTo,children}) => {
	const location = useLocation();
	const autenticado = useCheckLogin(devURL);

	return autenticado ? children : <Navigate to={redirectTo} state={{from: location}} replace />;
};

RequiereAuth.propTypes={
	devURL: PropTypes.string,
	redirectTo: PropTypes.string.isRequired,
	children: PropTypes.element.isRequired
};

const MainRouter = ({devURL,requiereLogin,children}) => (
	<BrowserRouter>
		<Routes>
			<Route path="/login" element={<Login devURL={devURL} />} />
			<Route
				path="/*"
				element={requiereLogin ? (
					<RequiereAuth devURL={devURL} redirectTo="/login">
						{children}
					</RequiereAuth>
				) : children
				}
			/>
		</Routes>
	</BrowserRouter>
);

MainRouter.propTypes={
	devURL: PropTypes.string,
	requiereLogin: PropTypes.bool,
	children: PropTypes.element.isRequired
};

export default MainRouter;