import { BrowserRouter as Router, Routes, Route, Outlet, useLocation, useNavigate } from 'react-router-dom';
import {useEffect, useState } from "react";

import { ToastContainer } from "react-toastify";
import {
  argbFromHex,
  themeFromSourceColor,
  applyTheme,
} from "@material/material-color-utilities";

import { AuthProvider } from "./auth/auth-provider"
import ping from "./auth/ping";

import Login from "./pages/login/login"
import Register from "./pages/register/register"

import Home from "./pages/home/home"
import Dashboard from "./pages/dashboard/dashboard"
import Settings from "./pages/settings/settings"
import useAuth from './auth/auth';


const PrivateRoute = () => {
  const { token, loading } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const [checked, setChecked] = useState(false);
  const [isValid, setIsValid] = useState(false);


  useEffect(() => {
    const checkAuth = async () => {
      if (!token) {
        setIsValid(false);
        setChecked(true);
        return;
      }
      const result = await ping(token);
      setIsValid(result);
      setChecked(true);
    };
    if (!loading) {
      checkAuth();
    }
  }, [token, loading]);

  if (loading || !checked) {
    return <div>Checking server availability...</div>;
  }

  if (!isValid) {
    navigate(`/login?to=${location.pathname}`);
  }
  else {
    return <Outlet />
  }
}


function App() {
  const theme = themeFromSourceColor(argbFromHex("ffddaf"));
  const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
  applyTheme(theme, { target: document.body, dark: systemDark });
  return (
    <AuthProvider>
    <>
      <ToastContainer
        position="top-right"
        autoClose={2000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick={false}
        rtl={false}
        theme={systemDark ? "light" : "dark"}
        // transition={Bounce}
      />
      <Router>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route path="/register" element={<Register />} />

          <Route element={<PrivateRoute />}>
            <Route path='/' element={<Home />} />
            <Route path='/dashboard' element={<Dashboard />} />
            <Route path='/settings' element={<Settings />} />
          </Route>

          <Route path="*" element={<div>404</div>} />
        </Routes>
      </Router>
    </>
    </AuthProvider>
  );
}

export default App;
