import { lazy, Suspense } from "react";
import LoadingScreen from "../app/LoadingScreen";
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import { useAuth0 } from "@auth0/auth0-react";
import Header from "app/Header";
import Logout from "pages/Logout";
import { ErrorBoundary } from "react-error-boundary";
import { getWhitelabel } from "services/whiteLabel";
import Ventilation from "pages/VentEditor";
import { useGlobalState } from "providers";

const DeviceHistory = lazy(() => import("pages/DeviceHistory"));
const DevicePage = lazy(() => import("pages/Device"));
const Devices = lazy(() => import("pages/Devices"));
const GroupsPage = lazy(() => import("pages/Groups"));
const GroupPage = lazy(() => import("pages/Group"));
const Teams = lazy(() => import("pages/Teams"));
const Users = lazy(() => import("pages/Users"));
const TeamPage = lazy(() => import("pages/Team"));
const BinPage = lazy(() => import("pages/Bin"));
const Bins = lazy(() => import("pages/Bins"));
const Mines = lazy(() => import("pages/Mines"));
const DeviceComponent = lazy(() => import("pages/DeviceComponent"));
const FieldMap = lazy(() => import("pages/FieldMap"));
const GrainBag = lazy(() => import("pages/grainBag"));
const Terminals = lazy(() => import("pages/Terminals"));
const Gate = lazy(() => import("pages/Gate"));
const AviationMap = lazy(() => import("pages/AviationMap"));
const ConstructionSiteMap = lazy(() => import("pages/ConstructionSiteMap"));
const Sites = lazy(() => import("pages/Sites"));
const Site = lazy(() => import("pages/Site"));
const Heaters = lazy(() => import("pages/Heaters"));
const Heater = lazy(() => import("pages/Heater"));
const Tasks = lazy(() => import("pages/Tasks"));
const Transactions = lazy(() => import("pages/Transactions"));
const BinCableEstimator = lazy(() => import("pages/BinCableEstimator"));
const APIDocs = lazy(() => import("pages/APIDocs"));
const Fields = lazy(()=> import("pages/Fields"));
const Marketplace = lazy(() => import("userFeatures/UserFeatures"))
export const appendToUrl = (appendage: number | string) => {
  const basePath = location.pathname.replace(/\/$/, ""); 
  return(`${basePath}/${appendage}`);
};

export default function Router() {

  const { isAuthenticated, loginWithRedirect, isLoading } = useAuth0();
  const whiteLabel = getWhitelabel();
  const [{ user }] = useGlobalState();

  const RelativeRoutes = () => {
    return (
      <Routes>
        <Route path="teams/*" element={<TeamsRoute/>} />
        <Route path="devices/*" element={<DevicesRoute/>} />
        <Route path="groups/*" element={<GroupsRoute/>} />
        <Route path="bins/*" element={<BinsRoute/>} />
        <Route path="mines/*" element={<MinesRoute/>} />
        <Route path="terminals/*" element={<TerminalGatesRoute />} />
        <Route path="jobsites/*" element={<JobsitesRoute />} />
        <Route path="heaters/*" element={<ObjectHeatersRoute />} />
      </Routes>
    )
  }

  const TeamsRoute = () => {
    return (
      <Routes>
        <Route
          path="" // "/settings/basic"
          element={<Teams />}
        />
        <Route
          path="/:teamID" // "/settings/basic"
          element={<TeamPage />}
        />
        <Route
          path="/:teamID/*" // "/settings/basic"
          element={<RelativeRoutes />}
        />
      </Routes>
    );
  };

  const DevicesRoute = () => {
    return (
      <div>
        <Routes>
          <Route
            key="Devices page route"
            path="" // "/settings/basic"
            element={<Devices key={"Devices page"} />}
          />
          <Route
            path="/:deviceID" // "/settings/basic"
            element={<DevicePage />}
          />
          <Route
            path="/:deviceID/components/:componentID" // "/settings/basic"
            element={<DeviceComponent />}
          />
          <Route
            path="/:deviceID/history" // "/settings/basic"
            element={<DeviceHistory />}
          />
          <Route
            path="/:deviceID/*" // "/settings/basic"
            element={<RelativeRoutes />}
          />
        </Routes>
      </div>
    );
  };

  const BinsRoute = () => {
    return (
      <div>
        <Routes>
          <Route
            key="Bins page route"
            path="" // "/settings/basic"
            element={<Bins key={"Bins page"} />}
          />
          <Route
            path="/:binID" // "/settings/basic"
            element={<BinPage />}
          />
          {/* <Route
            path="/:deviceID/components/:componentID" // "/settings/basic"
            element={<DeviceComponent />}
          />
          <Route
            path="/:deviceID/history" // "/settings/basic"
            element={<DeviceHistory />}
          /> */}
          <Route
            path="/:binID/*" // "/settings/basic"
            element={<RelativeRoutes />}
          />
        </Routes>
      </div>
    );
  };

  const MinesRoute = () => {
    return (
      <div>
        <Routes>
          <Route
            key="Mines page route"
            path="" // "/settings/basic"
            element={<Mines key={"Mines page"} />}
          />
          <Route
            path="/:mineKey" // "/settings/basic"
            element={<Ventilation />}
          />
          <Route
            path="/:mineKey/*" // "/settings/basic"
            element={<RelativeRoutes />}
          />
        </Routes>
      </div>
    );
  };

  const TerminalGatesRoute = () => {
    return (
      <div>
        <Routes>
          <Route
            key="Terminal page route"
            path="" // "/settings/basic"
            element={<Terminals key={"Terminals page"} />}
          />
          <Route
            path="/:gateKey" // "/settings/basic"
            element={<Gate />}
          />
          <Route
            path="/:gateKey/*" // "/settings/basic"
            element={<RelativeRoutes />}
          />
        </Routes>
      </div>
    );
  };

  const JobsitesRoute = () => {
    return (
      <div>
        <Routes>
          <Route
            key="Jobsite page route"
            path="" // "/settings/basic"
            element={<Sites key={"Jobsites page"} />}
          />
          <Route
            path="/:siteKey" // "/settings/basic"
            element={<Site />}
          />
          <Route
            path="/:siteKey/*" // "/settings/basic"
            element={<RelativeRoutes />}
          />
        </Routes>
      </div>
    );
  };

  const ObjectHeatersRoute = () => {
    return (
      <div>
        <Routes>
          <Route
            key="Heaters page route"
            path="" // "/settings/basic"
            element={<Heaters key={"Heaters page"} />}
          />
          <Route
            path="/:heaterKey" // "/settings/basic"
            element={<Heater />}
          />
          <Route
            path="/:heaterKey/*" // "/settings/basic"
            element={<RelativeRoutes />}
          />
        </Routes>
      </div>
    );
  };


  const GroupsRoute = () => {
    return (
      <div>
        <Routes>
          <Route
            path="/" 
            element={
              <ErrorBoundary FallbackComponent={ErrorFallback}>
                <GroupsPage />
              </ErrorBoundary>
            }
          />
          <Route
            path="/:groupID" 
            element={
              <ErrorBoundary FallbackComponent={ErrorFallback}>
                <GroupPage />
              </ErrorBoundary>
            }
          />
          <Route
            key="Devices page route"
            path="/:groupID/devices/" 
            element={<Devices key={"Devices page"}/>}
          />
          <Route
            path="/:groupID/devices/:deviceID" 
            element={<DevicePage />}
          />
          <Route
            path="/:groupID/devices/:deviceID/*" 
            element={<RelativeRoutes />}
          />
        </Routes>
      </div>
    );
  };

  if (isLoading) return null;
  if (!isAuthenticated) {
    loginWithRedirect()
    return (
      null
    )
  }

  function ErrorFallback({ error }: { error: Error }) {
    return <div>Something went wrong: {error.stack}</div>;
  }

  return (
    <Suspense fallback={<LoadingScreen />}>
      <BrowserRouter>
        <Header />
        <Routes>
          
          {/* Redirects */}
          <Route path="/callback" element={<Navigate to="/" />} />
          {/* <Route path="/team/:teamID" element={<Navigate to="/teams/:teamID" />} /> */}
          {/* <Route path="/device/:deviceID" element={<Navigate to="/devices/:devicesID" />} /> */}
          <Route path="" element={<Navigate to={whiteLabel.homePage ? whiteLabel.homePage : "/devices"} />} />
          
          {/* Page routes */}
          {/* <Route index element={<Typography>Hello!</Typography>} /> */}
          <Route path="users" element={<Users/>} />
          <Route path="tasks" element={<Tasks />} />
          <Route path="transactions" element={<Transactions />} />
          {user.hasFeature("installer") &&
            <Route path="cableEstimate" element={<BinCableEstimator />} />
          }
          {user.hasFeature("developer") &&
            <Route path="api" element={<APIDocs />} />
          }
          <Route path="fields" element={<Fields />} />
          <Route path="marketplace" element={<Marketplace />} />
          
          {/* Map pages */}
          <Route path="visualFarm" element={<FieldMap />} />
          <Route path="aviationMap" element={<AviationMap />} />
          <Route path="constructionMap" element={<ConstructionSiteMap />} />

          <Route path="/logout" element={<Logout />} />
          <Route path="grainbags/:bagID" element={<GrainBag />} />
{/* 
          <ErrorBoundary FallbackComponent={ErrorFallback}>
            <Route path="*" element={<RelativeRoutes/>} />
          </ErrorBoundary> */}

          <Route path="*" element={<RelativeRoutes/>} />
          
        </Routes>
      </BrowserRouter>
    </Suspense>
  )
}