import React, { lazy, Suspense, useEffect } from "react";
import { Routes, Route, Navigate, useNavigate } from "react-router-dom";
import { useSelector } from 'react-redux';
// import { toast } from "react-toastify";
import { useSessionManager } from "./hooks/useSessionManager";
import SessionWarningModal from "./pages/components/sessionWarningModal";
import AuthInterceptor from "./components/authinterceptor";

// home pages & dashboard
const Dashboard = lazy(() => import("./pages/dashboard"));

// auth pages (login pages)
const Login = lazy(() => import("./pages/auth/login"));
const Login2 = lazy(() => import("./pages/auth/login2"));
const Login3 = lazy(() => import("./pages/auth/login3"));
const Error = lazy(() => import("./pages/404"));

import Layout from "./layout/Layout";
import AuthLayout from "./layout/AuthLayout";

// components pages
const Button = lazy(() => import("./pages/components/button"));
const Dropdown = lazy(() => import("./pages/components/dropdown"));
const Badges = lazy(() => import("./pages/components/badges"));
const Colors = lazy(() => import("./pages/components/colors"));
const Typography = lazy(() => import("./pages/components/typography"));
const Alert = lazy(() => import("./pages/components/alert"));
const Progressbar = lazy(() => import("./pages/components/progress-bar"));
const Card = lazy(() => import("./pages/components/card"));
const Image = lazy(() => import("./pages/components/image"));
const Placeholder = lazy(() => import("./pages/components/placeholder"));
const Tooltip = lazy(() => import("./pages/components/tooltip-popover"));
const Modal = lazy(() => import("./pages/components/modal"));
const Carousel = lazy(() => import("./pages/components/carousel"));
const Pagination = lazy(() => import("./pages/components/pagination"));
const TabsAc = lazy(() => import("./pages/components/tab-accordion"));
const Video = lazy(() => import("./pages/components/video"));

const ComingSoonPage = lazy(() => import("./pages/utility/coming-soon"));
const UnderConstructionPage = lazy(() =>
  import("./pages/utility/under-construction")
);

const Profile = lazy(() => import("./pages/utility/profile"));
const IconPage = lazy(() => import("./pages/icons"));
import Loading from "@/components/Loading";

import MemberPage from "./pages/member";
import AddMember from "./pages/member/member-add";
import MemberEditOverview from "./pages/member/member-edit-overview";
import EditProfileMember from "./pages/member/member-edit-profile";
import MemberEditAddress from "./pages/member/member-edit-address";
import MemberAddAddress from "./pages/member/member-e-add-address";
import MemberEditOrder from "./pages/member/member-edit-order";
import MemberTopup from "./pages/member/member-edit-topup";
import MemberEditWallet from "./pages/member/member-edit-wallet";
import MemberEditVoucher from "./pages/member/member-edit-voucher";
import MemberEditPoint from "./pages/member/member-edit-point";
import EditDetailsMemberOrder from "./pages/member/member-e-edit-order";
import EditMemberAddress from "./pages/member/member-e-edit-address";
import MemberEditAdjustPoint from "./pages/member/member-edit-adjustpoint";
import OrgChart from "./pages/member/member-chart";
import MemberAdjustWallet from "./pages/member/member-edit-adjustwallet";
import { APIProvider } from "@vis.gl/react-google-maps";
import UserData from "./pages/settings/user";
import UserEdit from "./pages/settings/user/user-edit";
import AddNewUser from "./pages/settings/user/user-add";
import SlideshowSettings from "./pages/settings/slideshow";
import SlideshowAdd from "./pages/settings/slideshow/slideshow-add";
import SlideshowEdit from "./pages/settings/slideshow/slideshow-edit";
import CsvExport from "./pages/csv/index";

import SalesReport from "./pages/report/sales";
import PromoReport from "./pages/report/promo";
import ProductReport from "./pages/report/product";

import AllTasks from "./pages/task/all";
import THTasks from "./pages/task/th";
import TLTasks from "./pages/task/tl";
import FLSSTasks from "./pages/task/flss";
import LMTasks from "./pages/task/lm";
import TPTasks from "./pages/task/tp";

import AllTaskboard from "./pages/taskboard/all";
import THTaskboard from "./pages/taskboard/th";
import TLTaskboard from "./pages/taskboard/tl";
import FLSSTaskboard from "./pages/taskboard/flss";
import LMTaskboard from "./pages/taskboard/lm";
import TPTaskboard from "./pages/taskboard/tp";

function App() {
  const navigate = useNavigate();
  const { isAuth } = useSelector(state => state.auth);
  const {
    showWarning,
    timeLeft,
    timeLeftMs,
    expirationInfo,
    checkAutoLogin,
    extendSession,
    handleLogout,
    handleSessionExpiry, // Make sure this is destructured from useSessionManager
    checkSession // Make sure this is destructured from useSessionManager
  } = useSessionManager();

  useEffect(() => {
    console.log('App mounted, checking auto login...');
    if (!isAuth) {
      const autoLoggedIn = checkAutoLogin();
      if (autoLoggedIn) {
        console.log('Auto login successful, navigating to dashboard');
        navigate("/dashboard");
      } else {
        navigate("/login");
      }
    }
  }, []);


  useEffect(() => {
    if (isAuth && window.location.pathname === '/') {
      navigate("/dashboard");
    }
  }, [isAuth, navigate]);

  return (
    <main className="App relative">
      <AuthInterceptor />
      <APIProvider apiKey={import.meta.env.VITE_GOOGLE_MAPS_API_KEY}>
        <Routes>
          <Route path="/" element={<AuthLayout />}>
            <Route index element={<Login />} />
            <Route path="login2" element={<Login2 />} />
            <Route path="login3" element={<Login3 />} />
          </Route>

          <Route path="/*" element={<Layout />}>
            <Route index element={<Navigate to="/dashboard" />} />
            <Route path="dashboard" element={<Dashboard />} />

            <Route path="tasks">
              <Route index element={<Navigate to="all" />} />
              <Route path="all" element={< AllTasks />} />
              <Route path="th" element={< THTasks />} />
              <Route path="tl" element={< TLTasks />} />
              <Route path="flss" element={<FLSSTasks />} />
              <Route path="lm" element={<LMTasks />} />
              <Route path="tp" element={<TPTasks />} />
            </Route>

            <Route path="taskboards">
              <Route index element={<Navigate to="all" />} />
              <Route path="all" element={< AllTaskboard />} />
              <Route path="th" element={< THTaskboard />} />
              <Route path="tl" element={< TLTaskboard />} />
              <Route path="flss" element={<FLSSTaskboard />} />
              <Route path="lm" element={<LMTaskboard />} />
              <Route path="tp" element={<TPTaskboard />} />
            </Route>

            <Route path="settings">
              <Route index element={< UserData />} />
              <Route path="user" element={<UserData />} />
              <Route path="user/user-edit/:id" element={<UserEdit />} />
              <Route path="user/add_new_user" element={<AddNewUser />} />
              <Route path="slideshow_settings" element={< SlideshowSettings />} />
              <Route path="add_new_slideshow" element={< SlideshowAdd />} />
              <Route path="edit_slideshow/:id" element={< SlideshowEdit />} />
            </Route>

            {/* Member routes */}
            <Route path="member">
              <Route index element={<MemberPage />} />
              <Route path="add_new_member" element={<AddMember />} />
              <Route path="org_chart" element={<OrgChart />} />
              <Route path="member_overview/:id" element={<MemberEditOverview />} />
              <Route path="member_overview/member_address/:id" element={<MemberEditAddress />} />
              <Route path="member_overview/member_address/add_member_address/:id" element={<MemberAddAddress />} />
              <Route path="member_overview/member_address/edit_member_address/:addressId" element={<EditMemberAddress />} />
              <Route path="member_overview/member_order/:id" element={<MemberEditOrder />} />
              <Route path="member_overview/member_order/edit_order" element={<EditDetailsMemberOrder />} />
              <Route path="member_overview/member_point/:id" element={<MemberEditPoint />} />
              <Route path="member_overview/member_point/adjust_point/:id" element={<MemberEditAdjustPoint />} />
              <Route path="member_overview/member_profile/:id" element={<EditProfileMember />} />
              <Route path="member_overview/member_topup/:id" element={<MemberTopup />} />
              <Route path="member_overview/member_wallet/:id" element={<MemberEditWallet />} />
              <Route path="member_overview/member_wallet/adjust_wallet/:id" element={<MemberAdjustWallet />} />
              <Route path="member_overview/member_voucher/:id" element={<MemberEditVoucher />} />
            </Route>

            <Route path="csv-export">
              <Route index element={<CsvExport />} />
            </Route>
            <Route path="report">
              <Route index element={<Navigate to="sales" />} />
              <Route path="sales" element={<SalesReport />} />
              <Route path="promo" element={<PromoReport />} />
              <Route path="product" element={<ProductReport />} />
            </Route>

            {/* Components pages */}
            <Route path="button" element={<Button />} />
            <Route path="dropdown" element={<Dropdown />} />
            <Route path="badges" element={<Badges />} />
            <Route path="colors" element={<Colors />} />
            <Route path="typography" element={<Typography />} />
            <Route path="alert" element={<Alert />} />
            <Route path="progress-bar" element={<Progressbar />} />
            <Route path="card" element={<Card />} />
            <Route path="image" element={<Image />} />
            <Route path="Placeholder" element={<Placeholder />} />
            <Route path="tooltip-popover" element={<Tooltip />} />
            <Route path="modal" element={<Modal />} />
            <Route path="carousel" element={<Carousel />} />
            <Route path="Paginations" element={<Pagination />} />
            <Route path="tab-accordion" element={<TabsAc />} />
            <Route path="video" element={<Video />} />
            <Route path="profile" element={<Profile />} />
            <Route path="icons" element={<IconPage />} />

            <Route path="*" element={<Navigate to="/404" />} />
          </Route>

          <Route
            path="/404"
            element={
              <Suspense fallback={<Loading />}>
                <Error />
              </Suspense>
            }
          />
          <Route
            path="/coming-soon"
            element={
              <Suspense fallback={<Loading />}>
                <ComingSoonPage />
              </Suspense>
            }
          />
          <Route
            path="/under-construction"
            element={
              <Suspense fallback={<Loading />}>
                <UnderConstructionPage />
              </Suspense>
            }
          />
        </Routes>

        <SessionWarningModal
          isOpen={showWarning}
          timeLeft={timeLeft}
          timeLeftMs={timeLeftMs}
          onExtend={extendSession}
          onLogout={handleLogout}
        />
      </APIProvider>
    </main>
  );
}

export default App;