import React, { useState, useEffect, useContext, Suspense } from "react";
import { Navigate, Outlet, useLocation, Routes, Route, useNavigate } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "react-query";

import { EuiText, EuiLoadingSpinner, EuiEmptyPrompt } from "@elastic/eui";

import { AuthService, Login, Logout, Register, Confirm, ForgotPassword, ResetPassword } from "./features/auth";
import { TrialExpiredModal } from "./features/plan";
import { SetupStatusProvider } from "./features/setup";
import { SharePage } from "./features/share/SharePage";
import { GuestSharePage } from "./features/share/GuestSharePage";
import { GuestTeamPage } from "./features/share/GuestTeamPage";
import { MagicLinkVerifyPage } from "./features/share/MagicLinkVerifyPage";
import { SharedDashboardPage } from "./features/share/SharedDashboardPage";
import { SharedRunPage } from "./features/share/SharedRunPage";
import { EmbedChatPage } from "./features/embed/EmbedChatPage";
import { Home } from "./features/home";
import { Account } from "./features/account";
import { Admin } from "./features/admin";

import { Header } from "./components/header";
import { PWAInstallPrompt } from "./components/PWAInstallPrompt";
import ErrorBoundary from "./shared/components/ErrorBoundary";
import axios from "axios";
import apiClient from "./shared/services/api";
import { setNavigationCallback } from "./shared/services/navigation";

// Lazy load heavy components
const StackExpertApp = React.lazy(() => import("./components/app"));
const EnrollStack = React.lazy(() =>
  import("./features/settings").then(module => ({ default: module.EnrollStack }))
);
const Settings = React.lazy(() =>
  import("./features/settings").then(module => ({ default: module.Settings }))
);
const Monitoring = React.lazy(() =>
  import("./features/monitoring").then(module => ({ default: module.Monitoring }))
);
const Dashboard = React.lazy(() =>
  import("./pages/DashboardPage").then(module => ({ default: module.DashboardPage }))
);
const Hub = React.lazy(() =>
  import("./features/hub").then(module => ({ default: module.Hub }))
);
// V2.5-3: spectator page — watch a single run's tokens stream in real time.
const RunSpectatorView = React.lazy(() =>
  import("./features/chat").then(module => ({ default: module.RunSpectatorView }))
);

// Import debug utility
import { initDebugMode } from "./shared/utils/debug";

// Initialize debug mode (must be before any other console logs)
initDebugMode();

// Lazy load icons only when needed (performance optimization)
// Icons will be loaded on-demand by EUI components

// Create React Query client
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      cacheTime: 10 * 60 * 1000, // 10 minutes
      retry: 2,
      refetchOnWindowFocus: false,
    },
    mutations: {
      retry: 1,
    },
  },
});

// Loading component for Suspense fallback
function LoadingFallback() {
  return (
    <div style={{ marginTop: '48px', display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 'calc(100vh - 48px)' }}>
      <EuiEmptyPrompt
        icon={<EuiLoadingSpinner size="xl" />}
        title={<h2>Loading...</h2>}
      />
    </div>
  );
}

// Protected layout with auth check
function ProtectedLayout() {
  const user = AuthService.getCurrentUser();
  if (!user) {
    return <Navigate to="/login" />;
  }
  return (
    <ErrorBoundary context="Protected Area">
      <SetupStatusProvider>
        <Header />
        <TrialExpiredModal />
        <div style={{ paddingTop: "1rem" }}>
          <Suspense fallback={<LoadingFallback />}>
            <Outlet />
          </Suspense>
        </div>
      </SetupStatusProvider>
    </ErrorBoundary>
  );
}

// Public layout for auth pages — no app header, full-screen
function PublicLayout() {
  return (
    <ErrorBoundary context="Public Pages">
      <Outlet />
    </ErrorBoundary>
  );
}

function App() {
  const navigate = useNavigate();
  const [showAdminBoard, setShowAdminBoard] = useState(false);
  const [currentUser, setCurrentUser] = useState(undefined);
  const [trees, setTree] = useState({});

  // Set up navigation callback for services
  useEffect(() => {
    setNavigationCallback(navigate);
  }, [navigate]);

  return (
    <QueryClientProvider client={queryClient}>
      <ErrorBoundary context="Application Root">
        {/* <PWAInstallPrompt /> */}
        <Routes>
          {/* Embed widget — standalone, no app shell, no auth redirect.
              Rendered inside a third-party iframe via embed.js. */}
          <Route path="/embed/:linkId" element={<EmbedChatPage />} />

          {/* Public routes with shared layout */}
          <Route element={<PublicLayout />}>
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />
            <Route path="/confirm" element={<Confirm />} />
            <Route path="/logout" element={<Logout />} />
            <Route path="/forgot-password" element={<ForgotPassword />} />
            <Route path="/reset-password" element={<ResetPassword />} />
            {/* Share / guest access routes — no auth required */}
            <Route path="/share/team/:linkId" element={<GuestSharePage />} />
            <Route path="/share/team-view/:linkId" element={<GuestTeamPage />} />
            <Route path="/share/dashboard/:linkId" element={<GuestSharePage />} />
            <Route path="/share/run/:linkId" element={<GuestSharePage />} />
            <Route path="/share/verify/:token" element={<MagicLinkVerifyPage />} />
            <Route path="/share/dashboard-view/:shareTokenId" element={<SharedDashboardPage />} />
            <Route path="/share/run-view/:shareTokenId" element={<SharedRunPage />} />
          </Route>

          {/* Protected routes with shared layout */}
          <Route element={<ProtectedLayout />}>
            <Route path="/home" element={<Home />} />
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/account" element={<Account />} />
            <Route path="/app" element={<StackExpertApp http={apiClient} />} />
            <Route path="/app/teams" element={<StackExpertApp http={apiClient} />} />
            <Route path="/app/teams/:teamId" element={<StackExpertApp http={apiClient} />} />
            <Route path="/app/connectors" element={<StackExpertApp http={apiClient} />} />
            <Route path="/app/live" element={<StackExpertApp http={apiClient} />} />
            <Route path="/app/last_chats" element={<StackExpertApp http={apiClient} />} />
            <Route path="/app/integrations/:packageName" element={<StackExpertApp http={apiClient} />} />
            <Route
              path="/enroll"
              element={
                <EnrollStack
                  http={apiClient}
                  content={<EuiText>Enrollment content goes here</EuiText>}
                  extendedBorder={true}
                  restrictWidth={false}
                  centeredContent={true}
                />
              }
            />
            <Route path="/contexts" element={<Settings />} />
            <Route path="/monitoring" element={<Monitoring />} />
            {/* V2.5-3 — read-only spectator: watch a run's tokens stream live */}
            <Route path="/runs/:runId/live" element={<RunSpectatorView />} />
            <Route path="/hub" element={<Hub />} />
            <Route path="/admin" element={<Admin />} />
          </Route>

          {/* Root redirect */}
          <Route
            path="/"
            element={
              AuthService.getCurrentUser() ? (
                <Navigate to="/home" replace />
              ) : (
                <Navigate to="/login" replace />
              )
            }
          />
        </Routes>
      </ErrorBoundary>
    </QueryClientProvider>
  );
  // return (
  //   <BrowserRouter>
  //     <Switch>
  //       {/* <Route exact path="/" component={Login} /> */}
  //       {currentUser !== null && (
  //         <Route exact path="/app">
  //           <>
  //             <Header />
  //             <StackExpertApp http={axios} basename="/app/stack_expert" />
  //           </>
  //         </Route>
  //       )}
  //       {currentUser !== null && (
  //         <Route exact path="/enroll">
  //           <>
  //             <Header />
  //             <EnrollStack
  //               http={axios}
  //               content={<EuiText>Enrollment content goes here</EuiText>}
  //               extendedBorder={true}
  //               restrictWidth={false}
  //               centeredContent={true}
  //             />
  //           </>
  //         </Route>
  //       )}
  //       {currentUser !== null && (
  //         <Route exact path="/">
  //           <Redirect to="/app" />
  //         </Route>
  //       )}
  //       {currentUser === null && (
  //         <Route exact path="/">
  //           <Redirect to="/login" />
  //         </Route>
  //       )}
  //       {currentUser === null && (
  //         <Route exact path="/login">
  //           <Header />
  //           <Login />
  //         </Route>
  //       )}
  //     </Switch>
  //   </BrowserRouter>

  //   // <div>
  //   //   <nav className="navbar navbar-expand navbar-dark bg-dark">
  //   //     <Route path="/logout">
  //   //       <Logout />
  //   //     </Route>
  //   //     <Route path="/register">
  //   //       <Header />
  //   //       <Register />
  //   //     </Route>
  //   //     <Route path="/confirm">
  //   //       <Header />
  //   //       <Confirm />
  //   //     </Route>

  //   //     <Route path="/login">
  //   //       <Header />
  //   //       <Login />
  //   //     </Route>
  //   //     <Route path="/enroll">
  //   //       {currentUser ?
  //   //         <>
  //   //           <Header />
  //   //           <EnrollStack
  //   //             http={axios}
  //   //             content={<EuiText>Enrollment content goes here</EuiText>}
  //   //             extendedBorder={true}
  //   //             restrictWidth={false}
  //   //             centeredContent={true}
  //   //           />
  //   //         </>
  //   //       : <>
  //   //           <Header />
  //   //           <Login />
  //   //         </>
  //   //       }
  //   //     </Route>
  //   //     <Route path="/app">
  //   //       {currentUser ?
  //   //         <>
  //   //           <Header />
  //   //           <StackExpertApp http={axios} basename="/app/stack_expert" />
  //   //         </>
  //   //       : <>
  //   //           <Header />
  //   //           <Login />
  //   //         </>
  //   //       }
  //   //     </Route>
  //   //     <Route path="/" exact>
  //   //       {
  //   //         currentUser ?
  //   //           <Redirect to="/app" />
  //   //           // <StackExpertApp http={axios} basename="/app/stack_expert" />
  //   //         : <>
  //   //             <Header />
  //   //             <Login />
  //   //           </>

  //   //       }
  //   //     </Route>
  //   //   </nav>
  //   // </div>
  // );
}

export default App;
