import React, { Suspense, useEffect, useState } from "react";
import "./App.css";
import { Routes, Route, Navigate, useLocation } from "react-router-dom";
import { guestRouting } from "./routes/guestRouting";
import { getManagerRouting } from "./routes/managerRouting";
import { Box, ThemeProvider } from "@mui/material";
import createCache from "@emotion/cache";
import { prefixer } from "stylis";
import rtlPlugin from "stylis-plugin-rtl";
import { CacheProvider } from "@emotion/react";
import { theme } from "./data/theme";
import axios from "axios";
import { store } from "./lib/redux/store";
import { Loading } from "./components/loading/Loading";
import { useDispatch, useSelector } from "react-redux";
import { avicultureRouting } from "./routes/avicultureRouting";
import { Header } from "./layouts/header/Header";
import AdapterJalali from "@date-io/date-fns-jalali";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { cityRouting } from "./routes/cityRouting";
import { slaughterRouting } from "./routes/slaughterRouting";
import { Modal } from "./components/modal/Modal";
import { provinceFinancialRouting } from "./routes/provinceFinancialRouting";
import { vetFarmRouting } from "./routes/vetFarmRouting";
import Drawer from "./components/drawer/Drawer";
import { generalRouting } from "./routes/generalRouting";
import { StrictModal } from "./components/strict-modal/StrictModal";
import { StrictMissingHallNumber } from "./features/aviculture/components/strict-missing-hall-number/StrictMissingHallNumber";
import { driverRouting } from "./routes/driverRouting";
import { SidebarContextProvider } from "./contexts/SidebarContext";
import { BackDrop } from "./components/backdrop/BackDrop";
import { AppContextProvider } from "./contexts/AppContext";
import { Notif } from "./components/notif/Notif";
import { inspectorRouting } from "./routes/inspectorRouting";
// import bg from "./assets/images/bg.jpg";
import { Fallback } from "./layouts/fallback/Fallback";
import { slaughterHouseVetRouting } from "./routes/slaughterHouseVet";
import { ErrorBoundary } from "react-error-boundary";
import { ErrorFallback } from "./components/error-fallback/ErrorFallback";
import { LOG_OUT } from "./lib/redux/slices/userSlice";
import { adminRouting } from "./routes/adminRouting";
import { SetupAxios } from "./lib/axios/axios";
import { vetSupervisorRouting } from "./routes/vetSupervisorRouting";
import { jahadRouting } from "./routes/jahadRouting";
import { commerceRouting } from "./routes/commerceRouting";
import { cityCommerceRouting } from "./routes/cityCommerceRouting";
import { cityVetRouting } from "./routes/cityVetRouting";
import { cityJihadRouting } from "./routes/cityJihadRouting";
import { observatoryRouting } from "./routes/observatoryRouting";
import { provinceSupervisorRouting } from "./routes/provinceSupervisorRouting";
import { senfRouting } from "./routes/senfRouting";
import versionNumber from "./version.txt";
import { guildRoomRouting } from "./routes/guildRoomRouting";
import { posCompanyRouting } from "./routes/posCompanyRouting";
import { liveStockSupportRouting } from "./routes/liveStockSupportRouting";
import { chainCompanyRouting } from "./routes/chainCompanyRouting";
// import ChatButton from "./components/chat-system/ChatSystem";
import { supporterRouting } from "./routes/supporterRouting";
import { dispenserRouting } from "./routes/dispenserRouting";
import { cityPoultryRouting } from "./routes/cityPoultryRouting";
import { SiteMap } from "./layouts/site-map/SiteMap";
import { getRoleFromUrl } from "./utils/getRoleFromUrl";
import { parentCompanyRouting } from "./routes/parentCompanyRouting";
import { coldHouseStewardRouting } from "./routes/coldHouseStewardRouting";
import { cityGuildRouting } from "./routes/cityGuildRouting";
import { liveStockProvinceJahadRouting } from "./routes/LiveStockProvinceJahadRouting";
import { unionRouting } from "./routes/unionRouting";
import { cooperativeRouting } from "./routes/cooperativeRouting";
import { rancherRouting } from "./routes/rancherRouting";
import { barSquareRouting } from "./routes/barSquareRouting";
import { stewardRouting } from "./routes/stewardRouting";

const AppRouter = () => {
  const authToken = useSelector((state) => state.userSlice.authToken);
  const role = useSelector((state) => state.userSlice.role);

  let routes = [...guestRouting];
  let defaultRoute = "/";

  // const authToken = true;
  // const role = "Poultry";

  if (authToken) {
    routes = [...generalRouting, ...barSquareRouting];
    for (const singleRoleIndex in role) {
      if (Object.hasOwnProperty.call(role, singleRoleIndex)) {
        const element = role[singleRoleIndex];
        switch (element) {
          case "Admin":
            routes = [...routes, ...adminRouting, ...inspectorRouting];
            break;
          case "Poultry":
            routes = [...routes, ...avicultureRouting];
            break;
          case "CityOperator":
            routes = [...routes, ...cityRouting];
            break;
          case "KillHouse":
            routes = [...routes, ...slaughterRouting];
            break;
          case "ProvinceOperator":
            routes = [...routes, ...getManagerRouting("provinceOperator")];
            break;
          case "ProvinceFinancial":
            routes = [...routes, ...provinceFinancialRouting];
            break;
          case "ProvinceInspector":
            routes = [...routes, ...inspectorRouting];
            break;
          case "KillHouseVet":
            routes = [...routes, ...slaughterHouseVetRouting];
            break;
          case "VetFarm":
            routes = [...routes, ...vetFarmRouting];
            break;
          case "Driver":
            routes = [...routes, ...driverRouting];
            break;
          case "VetSupervisor":
            routes = [...routes, ...vetSupervisorRouting];
            break;
          case "Jahad":
            routes = [...routes, ...jahadRouting];
            break;
          case "Guilds":
            routes = [...routes, ...senfRouting];
            break;
          case "Steward":
            routes = [...routes, ...stewardRouting];
            break;
          case "Commerce":
            routes = [...routes, ...commerceRouting];
            break;
          case "ProvinceSupervisor":
            routes = [...routes, ...provinceSupervisorRouting];
            break;
          case "CityCommerce":
            routes = [...routes, ...cityCommerceRouting];
            break;
          case "CityVet":
            routes = [...routes, ...cityVetRouting];
            break;
          case "CityJahad":
            routes = [...routes, ...cityJihadRouting];
            break;
          case "Observatory":
            routes = [...routes, ...observatoryRouting];
            break;
          case "GuildRoom":
            routes = [...routes, ...guildRoomRouting];
            break;
          case "PosCompany":
            routes = [...routes, ...posCompanyRouting];
            break;
          case "LiveStockSupport":
            routes = [...routes, ...liveStockSupportRouting];
            break;
          case "SuperAdmin":
            routes = [...routes, ...getManagerRouting("SuperAdmin")];
            break;
          case "ChainCompany":
            routes = [...routes, ...chainCompanyRouting];
            break;
          case "AdminX":
            routes = [...routes, ...getManagerRouting("AdminX")];
            break;
          case "Supporter":
            routes = [...routes, ...supporterRouting];
            break;
          case "Dispenser":
            routes = [...routes, ...dispenserRouting];
            break;
          case "CityPoultry":
            routes = [...routes, ...cityPoultryRouting];
            break;
          case "ParentCompany":
            routes = [...routes, ...parentCompanyRouting];
            break;
          case "ColdHouseSteward":
            routes = [...routes, ...coldHouseStewardRouting];
            break;
          case "cityGuildRouting":
            routes = [...routes, ...cityGuildRouting];
            break;
          case "LiveStockProvinceJahad":
            routes = [...routes, ...liveStockProvinceJahadRouting];
            break;
          case "Union":
            routes = [...routes, ...unionRouting];
            break;
          case "Cooperative":
            routes = [...routes, ...cooperativeRouting];
            break;
          case "Rancher":
            routes = [...routes, ...rancherRouting];
            break;
          default:
        }
      }
    }
  }

  return (
    <Routes>
      {routes?.map((route) => {
        const { exact, Page, props } = route;
        return route.path.map((path) => (
          <Route
            exact={exact}
            path={path}
            key={path}
            element={
              <Suspense fallback={<Fallback />}>
                <Box>
                  <Page {...props} />
                </Box>
              </Suspense>
            }
          />
        ));
      })}
      <Route
        path="*"
        element={<Navigate to={defaultRoute ? defaultRoute : "/"} replace />}
      />
    </Routes>
  );
};

const cacheRtl = createCache({
  key: "muirtl",
  stylisPlugins: [prefixer, rtlPlugin],
});

const App = () => {
  const dispatch = useDispatch();
  const authToken = useSelector((state) => state.userSlice.authToken);
  const { pathname } = useLocation();
  // useEffect(() => {
  //   (function () {
  //     var cache = window.caches;
  //     cache.keys().then(function (keys) {
  //       keys.forEach(function (key) {
  //         cache.delete(key);
  //       });
  //     });
  //   })();
  // }, []);

  // check for necessary infos
  const { profile } = useSelector((state) => state.avicultureSlice);
  const [neededInfoMissingHall, setNeededInfoMissingHall] = useState([]);

  // const { selectedRoles } = useSelector((state) => state.fileSlice);

  // useEffect(() => {
  //   if (authToken) {
  //     dispatch(avicultureGetProfile());
  //     if (!selectedRoles?.length) {
  //       dispatch(CHANGE_SELECTED_ROLES(role));
  //     }
  //     if (isFirstLogin) {
  //       switch (role[0]) {
  //         case "Admin":
  //           break;
  //         case "Poultry":
  //           navigate(ROUTE_AVICULTURE_REQUESTS);
  //           break;
  //         case "CityOperator":
  //           navigate(ROUTE_CITY_REQUESTS);
  //           break;
  //         case "KillHouse":
  //           navigate(ROUTE_SLAUGHTER_REQUESTS);
  //           break;
  //         case "ProvinceOperator":
  //           navigate(ROUTE_PROVINCE_REQUESTS);
  //           break;
  //         case "ProvinceFinancial":
  //           navigate(ROUTE_PROVINCE_FINANCIAL_REQUESTS);
  //           break;
  //         case "ProvinceInspector":
  //           break;
  //         case "KillHouseVet":
  //           navigate(ROUTE_SLAUGHTER_HOUSE_VET_REQUESTS);
  //           break;
  //         case "VetFarm":
  //           navigate(ROUTE_VETFARM_ROUTE_ALLOCATIONS);
  //           break;
  //         case "Driver":
  //           break;
  //         case "VetSupervisor":
  //           navigate(ROUTE_VETـSUPERVISOR_ALLOCATIONS);
  //           break;
  //         case "CityVet":
  //           navigate(ROUTE_CITYVET_ROUTE_ALLOCATIONS);
  //           break;
  //         case "Observatory":
  //           navigate(ROUTE_OBSERVATORY_STATICS);
  //           break;
  //         case "Jahad":
  //           break;
  //       }
  //       dispatch(IS_FIRST_LOGIN(false));
  //     }
  //   }
  // }, [authToken]);

  useEffect(() => {
    setOpen(false);
    if (authToken && profile) {
      for (const iterator of profile.aviculture) {
        if (!iterator.numberOfHalls) {
          setOpen(true);
          setNeededInfoMissingHall([
            {
              title: "NUMBER_OF_HALLS",
              data: {
                ...iterator,
              },
            },
          ]);
        }
      }
    }
  }, [authToken, profile]);

  useEffect(() => {
    if (!authToken || profile === null) {
      setOpen(false);
    }
  }, [authToken, profile]);

  // useEffect(() => {
  //   if (authToken) {
  //     dispatch(provinceGetPolicyAvicultureCommitService());
  //   }
  // }, []);

  //buildchange
  // useEffect(() => {
  //   let name = "Arta-System";
  //   let version = "7";

  //   const last_version = localStorage.getItem(`${name}-Version`);
  //   if (last_version !== version) {
  //     localStorage.setItem(`${name}-Version`, version);
  //     dispatch(LOG_OUT());
  //     // window.location.reload(true);
  //   }
  // }, []);

  const [visibleSiteMap, setVisibleSiteMap] = useState(false);

  useEffect(() => {
    setVisibleSiteMap(authToken && getRoleFromUrl());
  }, [window.location.href, window.location.pathname, pathname]);

  useEffect(() => {
    if (
      window.location.search.includes("refresh") &&
      !window.location.search.includes("finalAmount")
    ) {
      window.location.href = window.location.pathname;
    }
  }, []);

  const hardRefresh = () => {
    const currentUrl = window.location.href;
    const newUrl = `${currentUrl}?refresh=${new Date().getTime()}`;
    window.location.href = newUrl;
  };

  useEffect(() => {
    const uniqueQueryParam = `?v=${new Date().getTime()}`;
    fetch(`${versionNumber}${uniqueQueryParam}`)
      .then((response) => response.text())
      .then((numberText) => {
        const numberFromTxt = numberText.toString();
        const lastVersion = localStorage.getItem("AppVersion");
        console.log("compare versions", numberFromTxt, lastVersion);
        if (
          !lastVersion ||
          lastVersion.toString() !== numberFromTxt.toString()
        ) {
          localStorage.setItem("AppVersion", numberFromTxt.toString());

          if ("caches" in window) {
            caches.keys().then((names) => {
              names.forEach((name) => {
                caches.delete(name);
              });
            });
            hardRefresh();

            // dispatch(
            //   OPEN_MODAL({
            //     title: "ورژن جدید در دسترس است",
            //     content: (
            //       <>
            //         <Grid container gap={SPACING.SMALL} justifyContent="center">
            //           <Typography variant="body2">
            //             جهت بهره مندی از امکانات جدید لطفا مرورگر خود را با زدن
            //             کلیدهای CTRL و F5 مجددا بارگزاری کنید.
            //           </Typography>
            //           <Button
            //             variant="outlined"
            //             onClick={() => {
            //               dispatch(CLOSE_MODAL());
            //             }}
            //           >
            //             متوجه شدم
            //           </Button>
            //         </Grid>
            //       </>
            //     ),
            //   })
            // );
          }
        }
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  }, [window.location.pathname]);

  const [open, setOpen] = React.useState(false);
  //   const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  return (
    <CacheProvider value={cacheRtl}>
      <ThemeProvider theme={theme}>
        <LocalizationProvider dateAdapter={AdapterJalali}>
          <ErrorBoundary
            FallbackComponent={ErrorFallback}
            onReset={() => {
              dispatch(LOG_OUT());
            }}
          >
            <Suspense fallback={<Fallback />}>
              <AppContextProvider>
                <div
                  className="App"
                  style={
                    {
                      // background: !authToken ? `url("${bg}")` : null,
                      // height: !authToken ? "100vh" : "auto",
                    }
                  }
                >
                  <SidebarContextProvider>
                    {authToken && <Header />}
                    {visibleSiteMap && <SiteMap />}

                    {/* {authToken && <ChatButton />} */}
                    <BackDrop />
                    <Notif />
                  </SidebarContextProvider>
                  <AppRouter />
                </div>
                {neededInfoMissingHall.map((item, i) => {
                  let modalTitle = "";
                  const modalContent = (
                    <StrictMissingHallNumber
                      avicultureKey={item.data?.key}
                      name={item.data?.unitName}
                      id={item.data?.breedingUniqueId}
                      handleClose={handleClose}
                    />
                  );
                  if (item.title === "NUMBER_OF_HALLS") {
                    modalTitle = "ثبت تعداد سالن ها";
                  }
                  return (
                    <StrictModal
                      key={"modal" + i}
                      title={modalTitle}
                      content={modalContent}
                      open={open}
                    />
                  );
                })}
                <Drawer />
                <Modal />
                <Loading />
              </AppContextProvider>
            </Suspense>
          </ErrorBoundary>
        </LocalizationProvider>
      </ThemeProvider>
    </CacheProvider>
  );
};

SetupAxios(axios, store);

export default App;
