import React, { useState, useEffect } from "react";
import "./App.scss";
import "antd/dist/antd.css";
import { useNavigate } from "react-router-dom";
import { setupInterceptor } from "./common/http";
import { useDispatch } from "react-redux/es/exports";
import { LOCAL_STORAGE } from "./constants/index";
import { removeUserInfo } from "./store/UserSlice";
import AuthService from "./services/Auth";
import store from "./store";
import { MainRoutes } from "./router/Routes";

function App() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [mounted, setMounted] = useState(false);

  const relogin = () => {
    dispatch(removeUserInfo());
    navigate("/login");
  };

  const errRedirect = (errCode) => {
    const routes = {
      404: "/404",
      500: "/500",
      501: "/501",
      zabbixErr: '/zabbixErr',
      databaseErr: '/databaseErr',
      error: "/error",
      config: "/setup",
      networkErr: "/networkErr",
    };
    navigate(routes[errCode] || "/");
  };

  useEffect(() => {
    const preloader = document.getElementById('preloader');
    if (preloader) {
      preloader.style.display = 'none';
    }
    setupInterceptor(store, relogin, errRedirect);
    setMounted(true);
  }, []);

  return mounted ? <MainRoutes /> : null;
}

export default App;
