import { useEffect, lazy, Suspense, useRef } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { App as CapacitorApp } from '@capacitor/app';
import { Routes, Route } from 'react-router-dom';
import { useSelector } from 'react-redux';
import ProtectedRoutes from './ProtectedRoutes';
import SelfBooking from './Pages/SelfBooking/SelfBooking.jsx';
import { isMobile, isIOS } from 'react-device-detect';
import { routesConfig } from './routesConfig';
import { GlobalItemCard } from './Features/BookingScreen/BookingData/BookingData.js';
import { clearSession, getSession } from './Services/Others.js';

const KisokSelBooking = lazy(
  () => import('./Pages/SelfBooking/KisokSelBooking')
);
const IndividualBooking = lazy(
  () => import('./Pages/SelfBooking/IndividualBooking')
);

const commonSubDir = import.meta.env.ENV_COMMON_BASE_URL;
const subDirectory = import.meta.env.ENV_BASE_URL;
import '../ownLib/my-ui-lib.css';
import CardSkeleton from './Components/Skeleton/CardSkeleton.jsx';
import CustomerMenuPage from './Pages/Reports/MenuQRCode/CustomerMenuPage.jsx';
import WeightScaleApp from './Pages/BookingScreen/WeightscaleApp.jsx';
import useSubscriptionManager from './useSubscriptionManager.js';
import useSessionManager from './useSessionManager.js';
import ExtendSubscriptionModal from './Pages/ExtentedModal/ExtendSubscriptionModal.jsx';

const isCapacitor = () => !!window.Capacitor?.isNativePlatform?.();

// ✅ Define your home/exit pages here
const HOME_PAGES = [
  '/landing-page/home',
  '/home/landing-page/home',
  'app-page/home', // android minimize
];

const LOGIN_PAGES = ['signin', 'login', 'auth'];

const AppRoutes = () => {
  const ItemCard = useSelector(GlobalItemCard);
  const { sessionData, logout } = useSessionManager(ItemCard);
  const {
    remainingDays,
    handleCancel,
    freeExtend,
    extendModel,
    handlePay,
    setExtendModel,
  } = useSubscriptionManager(sessionData, logout);
  const location = useLocation();
  const navigate = useNavigate();

  // ✅ Flag to prevent stack push when back button navigates
  const isBackNav = useRef(false);

  // ✅ Build navigation stack
  useEffect(() => {
    // Skip pushing to stack when back button caused this navigation
    if (isBackNav.current) {
      isBackNav.current = false;
      return;
    }

    try {
      const path = location.pathname + (location.search || '');

      // Don't track login pages
      if (LOGIN_PAGES.some((p) => path.includes(p))) return;

      const raw = sessionStorage.getItem('navStack');
      let stack = raw ? JSON.parse(raw) : [];

      if (stack.length === 0 || stack[stack.length - 1] !== path) {
        stack.push(path);
        if (stack.length > 50) stack = stack.slice(-50);
        sessionStorage.setItem('navStack', JSON.stringify(stack));
        console.log('📍 Stack:', stack);
      }
    } catch (e) {}
  }, [location.pathname, location.search]);

  // ✅ Web — block browser back button
  useEffect(() => {
    if (isCapacitor()) return; // Android handled separately

    const handlePopState = () => {
      const currentPath = location.pathname;

      // On home page — just stay, don't redirect
      if (HOME_PAGES.some((p) => currentPath.includes(p))) {
        window.history.go(1); // stay here
        return;
      }

      const SessionId = getSession('SessionId');
      if (!SessionId) {
        alert(
          'Session invalid and Unauthorized action detected. Redirecting to login...'
        );
        clearSession();
        window.location.replace(`${commonSubDir}`);
      } else {
        window.history.go(1);
      }
    };

    // Add event listener on mount
    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, [location.pathname]);

  // ✅ Android — Capacitor back button
  useEffect(() => {
    if (!isMobile && !isIOS && !isCapacitor()) return;

    let backButtonListener;

    const setupBackButton = async () => {
      try {
        backButtonListener = await CapacitorApp.addListener(
          'backButton',
          async () => {
            try {
              const currentPath = location.pathname + (location.search || '');
              console.log('🔙 Back pressed:', currentPath);

              // 🏠 Home page → minimize
              if (HOME_PAGES.some((p) => currentPath.includes(p))) {
                if (isCapacitor()) {
                  await CapacitorApp.minimizeApp();
                }
                return;
              }

              // 🚪 Login page → exit
              if (LOGIN_PAGES.some((p) => currentPath.includes(p))) {
                if (isCapacitor()) {
                  await CapacitorApp.exitApp();
                }
                return;
              }

              const raw = sessionStorage.getItem('navStack');
              let stack = raw ? JSON.parse(raw) : [];

              while (stack.length && stack[stack.length - 1] === currentPath) {
                stack.pop();
              }

              if (stack.length) {
                const previous = stack[stack.length - 1];

                if (LOGIN_PAGES.some((p) => previous.includes(p))) {
                  const home = '/landing-page/home';
                  sessionStorage.setItem('navStack', JSON.stringify([home]));
                  isBackNav.current = true;
                  navigate(home);
                  return;
                }

                sessionStorage.setItem('navStack', JSON.stringify(stack));
                isBackNav.current = true;
                navigate(previous);
              } else {
                const home = '/landing-page/home';
                sessionStorage.setItem('navStack', JSON.stringify([home]));
                isBackNav.current = true;
                navigate(home);
              }
            } catch (err) {
              console.error('Back handler error:', err);
              navigate('/landing-page/home');
            }
          }
        );
      } catch (err) {
        console.error('Listener error:', err);
      }
    };

    setupBackButton();

    return () => {
      try {
        backButtonListener?.remove();
      } catch (err) {}
    };
  }, [navigate, location.pathname, location.search]);

  if (extendModel) {
    return (
      <ExtendSubscriptionModal
        onClose={handleCancel}
        onPayNow={handlePay}
        onContinueWithCredits={freeExtend}
      />
    );
  }
  return (
    <Suspense fallback={<CardSkeleton />}>
      <Routes>
        <Route
          path={`${subDirectory}selfBooking/:SelfBookingId`}
          element={<SelfBooking />}
        />
        <Route
          path={`${subDirectory}MenuQRCode`}
          element={<CustomerMenuPage />}
        />
        <Route
          path={`${subDirectory}weightscaleapp`}
          element={<WeightScaleApp />}
        />
        <Route
          path={`${subDirectory}kioskSelfBooking`}
          element={<KisokSelBooking />}
        />

        <Route
          path={`${subDirectory}kiosk-individual-self-booking`}
          element={<IndividualBooking />}
        />
        <Route
          path="/*"
          element={<ProtectedRoutes routesConfig={routesConfig} />}
        />
      </Routes>
    </Suspense>
  );
};

export default AppRoutes;
