import React, { Suspense, useEffect, useState } 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 SideBar from './components/layout/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';
import AgenticFeedPage from './pages/AgenticFeed';
import AIReadiness from './pages/AIReadiness';
import AiVisibility from './pages/AiVisibility';
import ProductImprovements from './pages/ProductImprovements';
import LlmTxtPage from './pages/LlmTxt';
import AgentAnalytics from './pages/AgentAnalytics';
import KnowledgeBase from './pages/KnowledgeBase';
import ContentGenerator from './pages/ContentGenerator';
import Campaigns from './pages/Campaigns';
import CampaignCreate from './pages/CampaignCreate';
import CampaignDetail from './pages/CampaignDetail';
import CatalogQuality from './pages/CatalogQuality';
import Dashboard from './pages/Dashboard';
import { useAccessControl } from './hooks/useAccessControl';
import PreviewBanner from './components/PreviewBanner';
import { updatePreviewMode } from './service/user/user.service';
import TawkTo from './components/TawkTo';
import VerificationModal from './components/VerificationModal';

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

  const [shouldLoadTawkTo, setShouldLoadTawkTo] = useState<boolean>(false);

  useEffect(() => {
    const timeout = setTimeout(() => setShouldLoadTawkTo(true), 5000);
    return () => clearTimeout(timeout);
  }, []);

  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 { canAccessAllRoutes, canSeeBulkUpload } = useAccessControl(user);

  const handleActivatePreview = async () => {
    if (!token) return;
    try {
      await updatePreviewMode({ token, preview_mode: true });
      if (user) setUser({ ...user, preview_mode: true });
    } catch (error) {
      console.error('Error enabling preview mode:', error);
    }
  };

  const handleDeactivatePreview = async () => {
    if (!token) return;
    try {
      await updatePreviewMode({ token, preview_mode: false });
      if (user) setUser({ ...user, preview_mode: false });
    } catch (error) {
      console.error('Error disabling preview mode:', error);
    }
  };

  return (
    <Router>
      <div
        id="recomaze-app-container"
        className="flex flex-col w-full xl:mx-auto xl:w-[90%] 2xl:w-[80%] h-full mx-auto bg-white"
        style={{ position: 'relative' }}
      >
        <VerificationModal />
        <SideBar />
        <div className="px-4 pt-4">
          <PreviewBanner
            token={token}
            domain={recomaze_ai_personalization_env?.domain ?? null}
            previewMode={user?.preview_mode ?? false}
            documentationReady={user?.first_documentation_created ?? false}
            onActivatePreview={handleActivatePreview}
            onDeactivatePreview={handleDeactivatePreview}
          />
        </div>
        {!canAccessAllRoutes ? (
          <Routes>
            <Route path="/" element={<Pricing />}></Route>
          </Routes>
        ) : (
          <Routes>
            <Route
              path="/"
              element={
                recomaze_ai_personalization_env?.last_auth_action ===
                'sign_up' ? (
                  <Onboarding />
                ) : (
                  <Dashboard />
                )
              }
            />
            <Route path="/customization" element={<Customization />} />
            <Route path="/catalog-quality" element={<CatalogQuality />} />
            <Route path="/agent-analytics" element={<AgentAnalytics />} />
            <Route path="/agentic-feed" element={<AgenticFeedPage />} />
            <Route path="/ai-readiness" element={<AIReadiness />} />
            <Route path="/ai-visibility" element={<AiVisibility />} />
            <Route path="/llm" element={<LlmTxtPage />} />
            <Route
              path="/product-improvements"
              element={canSeeBulkUpload ? <ProductImprovements /> : <Pricing />}
            />
            <Route path="/content-generator" element={<ContentGenerator />} />
            <Route path="/campaigns" element={<Campaigns />} />
            <Route path="/campaigns/create" element={<CampaignCreate />} />
            <Route path="/campaigns/:id" element={<CampaignDetail />} />
            <Route path="/knowledge-base" element={<KnowledgeBase />} />
            <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>
        )}
        {shouldLoadTawkTo && (
          <Suspense fallback={<div>Loading Chat Widget...</div>}>
            <TawkTo />
          </Suspense>
        )}
      </div>
    </Router>
  );
};

export default App;
