import React, { useEffect } from 'react';
import { HashRouter as Router, Routes, Route } from 'react-router-dom';

import { recomaze_ai_personalization_env } from './env';
import Support from './pages/Support';
import Settings from './pages/Settings';
import Dashboard from './pages/Dashboard';
import SideBar from './components/SideBar';
import Customization from './pages/Customization';
import ImportProducts from './pages/ImportProducts';
import { useAppStateContext } from './context/user.data.context';
import Onboarding from './pages/Onboarding';
import Pricing from './pages/Pricing';

const App = (): JSX.Element => {
  const {
    token,
    clientId,
    user,
    setToken,
    setClientId,
    fetchUser,
    setCanUseWpApi,
  } = useAppStateContext();

  useEffect(() => {
    if (!token && recomaze_ai_personalization_env?.auth?.token)
      setToken(recomaze_ai_personalization_env?.auth?.token);
    if (!clientId && recomaze_ai_personalization_env?.auth?.client_id)
      setClientId(recomaze_ai_personalization_env?.auth?.client_id);
    if (!user && token) fetchUser();
    if (!recomaze_ai_personalization_env?.can_use_wp_api) setCanUseWpApi(false);
  }, [token, clientId]);

  const hasPaidPlan =
    Boolean(user?.plan_snapshot) &&
    user?.stripe_subscription_status === 'active';
  const hasFreeTrial = (user?.trial_days ?? 0) > 0 && !hasPaidPlan;

  const hasValidAccessWindow = (() => {
    const until = user?.subscription_access_until as string | undefined;
    if (!until) return false;
    const d = new Date(until);
    return !Number.isNaN(d.getTime()) && d.getTime() >= Date.now();
  })();

  const canAccessAllRoutes =
    hasPaidPlan ||
    hasFreeTrial ||
    user?.has_active_subscription ||
    user?.plan_snapshot ||
    hasValidAccessWindow;

  return (
    <Router>
      <div className="flex flex-col w-full xl:mx-auto xl:w-[90%] 2xl:w-[80%] h-full mx-auto bg-white">
        <SideBar />
        {!canAccessAllRoutes ? (
          <Routes>
            <Route path="/" element={<Pricing />}></Route>
          </Routes>
        ) : (
          <Routes>
            <Route
              path="/"
              element={
                recomaze_ai_personalization_env?.last_auth_action ===
                'sign_up' ? (
                  <Onboarding />
                ) : (
                  <Customization />
                )
              }
            />
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/pricing" element={<Pricing />} />
            <Route path="/onboarding" element={<Onboarding />} />
            <Route path="/import" element={<ImportProducts />} />
            <Route path="/settings" element={<Settings />} />
            <Route path="/support" element={<Support />} />
          </Routes>
        )}
      </div>
    </Router>
  );
};

export default App;
