import { Routes, Route, useNavigate, useLocation } from "react-router";
//
import MainPage from "./pages/MainPage";
import SearchPage from "./pages/SearchPage";
import PageBody from "./pages/PageBody";
import BookPage from "./pages/BookPage";
import AccountPage from "./pages/account/AccountPage";
import AuthPage from "./pages/AuthPage";
//
import {
  argbFromHex,
  themeFromSourceColor,
  applyTheme,
} from "@material/material-color-utilities";
import axios from "axios";
import { useEffect, useState } from "react";
import Reader from "./pages/Reader";
import Offline from "./pages/Offline";
import { ToastContainer } from "react-toastify";

import "react-toastify/dist/ReactToastify.css";
import NotFound from "./pages/NotFound";
import Collections from "./pages/account/Collections";
import Main from "./pages/account/Main";
import CollectionPage from "./pages/account/CollectionPage";
import OOBE from "./pages/OOBE/OOBE";
import OOBEWelcome from "./pages/OOBE/OOBEWelcome";
import OOBECreateUser from "./pages/OOBE/OOBECreateUser";
import UploadBook from "./pages/account/UploadBook";
import ShelvePage from "./pages/account/ShelvePage";

const PWAPage = () => {
  const navigate = useNavigate();
  useEffect(() => {
    let lastReadBook = localStorage.getItem("lastReadBook");
    if (lastReadBook !== null) {
      navigate(`/reader/${lastReadBook}`);
    } else {
      navigate("/account");
    }
  });
  return <></>;
};

function App() {
  const [checked, setChecked] = useState(false);

  const theme = themeFromSourceColor(argbFromHex("ffddaf"));
  const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
  applyTheme(theme, { target: document.body, dark: systemDark });
  const navigate = useNavigate();
  const location = useLocation();
  useEffect(() => {
    axios
      .get("/ping", { timeout: 5000 })
      .then(() => {
        window.onLine = true;
        setChecked(true);
      })
      .catch((error) => {
        if (error.response === undefined) {
          window.onLine = false;
        } else {
          if (error.response.status === 401) {
            window.onLine = true;
            if (
              location.pathname !== "/login" &&
              !location.pathname.startsWith("/oobe")
            ) {
              console.log("redir");
              navigate(`/login?to=${location.pathname}`);
            }
          } else {
            window.onLine = false;
          }
        }
        setChecked(true);
      });
  }, []);
  if (!checked) {
    return <span>проверка соединения с сервером...</span>;
  }

  return (
    <>
      <ToastContainer theme={systemDark ? "dark" : "light"} autoClose={2000} />
      <Routes>
        <Route path="/login" element={<AuthPage />} />
        <Route path="/pwa" element={<PWAPage />} />
        <Route path="/oobe" element={<OOBE />}>
          <Route index element={<OOBEWelcome />} />
          <Route path="create-user" element={<OOBECreateUser />} />
        </Route>
        {/*<Route index element={<MainPage/>} />*/}
        <Route element={<PageBody />}>
          <Route path="/" element={<AccountPage />}>
            <Route index element={<Main />} />
            <Route path="collections" element={<Collections />} />
            <Route path="collection/:id" element={<CollectionPage />} />
            <Route path="shelve" element={<ShelvePage />} />
            <Route path="settings" element={<p>404</p>} />
            <Route path="upload" element={<UploadBook />} />
          </Route>
          <Route path="/search" element={<SearchPage />} />
          <Route path="/book/:id" element={<BookPage />} />
          <Route path="/reader/:id" element={<Reader />} />
          <Route path="/offline" element={<Offline />} />
          <Route path="*" element={<NotFound />} />
        </Route>
      </Routes>
    </>
  );
}

export default App;
