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

import { recomaze_ai_personalization_env } from './env';
import { SidebarProvider, useSidebar } from './context/sidebar.context';
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 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 VerificationModal from './components/VerificationModal';
import ErrorBoundary from './components/ErrorBoundary';

// In-flow top bar shown only on small screens; opens the off-canvas sidebar.
const MobileTopBar = (): JSX.Element => {
  const { setMobileOpen } = useSidebar();
  const logo = recomaze_ai_personalization_env?.plugin_icon;

  return (
    <div className="sticky top-8 z-30 flex items-center gap-2 border-b border-gray-200 bg-white px-4 py-2 lg:hidden">
      <button
        type="button"
        onClick={() => setMobileOpen(true)}
        aria-label="Open navigation"
        className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-gray-200 text-gray-700 outline-none focus:outline-none"
      >
        <LuMenu className="h-5 w-5" aria-hidden />
      </button>
      {logo ? (
        <img src={logo} alt="Recomaze" className="h-6 w-6 rounded" />
      ) : null}
      <span className="text-sm font-semibold text-gray-900">Recomaze</span>
    </div>
  );
};

const App = (): JSX.Element => {
  const {
    token,
    clientId,
    user,
    setUser,
    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 { 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>
      <SidebarProvider>
        <div
          id="recomaze-app-container"
          className="flex w-full bg-white"
          style={{ position: 'relative' }}
        >
          <SideBar />
          <div className="flex min-w-0 flex-1 flex-col">
            <MobileTopBar />
            <main id="main" className="min-w-0">
              <VerificationModal />
              <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>
              ) : (
                <ErrorBoundary>
                <Routes>
                  <Route path="/" element={<Dashboard />} />
                  <Route path="/dashboard" element={<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="/import" element={<ImportProducts />} />
                  <Route path="/settings" element={<Settings />} />
                  <Route path="/support" element={<Support />} />
                </Routes>
                </ErrorBoundary>
              )}
            </main>
          </div>
        </div>
      </SidebarProvider>
    </Router>
  );
};

export default App;
