import React, { useMemo } from "react";
import App from "./App";
import { BrowserRouter, Navigate, Route, Routes, useLocation } from "react-router-dom";
import { useTuitioToken } from "@flare/tuitio-client-react";
import LoginContainer from "../features/login/components/LoginContainer";

const PrivateRoute = ({ children }: { children: React.ReactElement }): React.ReactElement => {
  const { valid } = useTuitioToken();
  const location = useLocation();
  return valid ? (
    children
  ) : (
    <Navigate
      to="/login"
      state={{
        from: location.pathname,
        search: location.search
      }}
    />
  );
};

const PublicRoute = ({ children }: { children: React.ReactElement }): React.ReactElement => {
  const location = useLocation();
  const { valid } = useTuitioToken();
  const to = useMemo(() => {
    if (location.state?.from) {
      return location.state.from + location.state.search;
    }
    return "/";
  }, [location.state?.from, location.state?.search]);
  return valid ? (
    <Navigate
      to={to}
      state={{
        from: location.pathname
      }}
    />
  ) : (
    children
  );
};

const AppRouter: React.FC = () => {
  return (
    <BrowserRouter basename={import.meta.env.PUBLIC_URL || ""}>
      <Routes>
        <Route path="/" element={<Navigate to="/dashboard" />} />
        <Route
          path="/login"
          element={
            <PublicRoute>
              <LoginContainer />
            </PublicRoute>
          }
        />
        <Route
          path="/*"
          element={
            <PrivateRoute>
              <App />
            </PrivateRoute>
          }
        />
      </Routes>
    </BrowserRouter>
  );
};

export default AppRouter;
