import { lazy, Suspense, useEffect } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";
import { AppLayout } from "@/components/layout/AppLayout";
import { ErrorBoundary } from "@/components/shared/ErrorBoundary";
import { LoadingSpinner } from "@/components/shared/LoadingSpinner";
import { Toaster } from "@/components/ui/toaster";
import { useUiStore } from "@/stores/ui";
import i18n from "@/i18n";

const LoginPage = lazy(() => import("@/pages/login/LoginPage").then((module) => ({ default: module.LoginPage })));
const DashboardPage = lazy(() => import("@/pages/dashboard/DashboardPage").then((module) => ({ default: module.DashboardPage })));
const AgentListPage = lazy(() => import("@/pages/agents/AgentListPage").then((module) => ({ default: module.AgentListPage })));
const SessionChatPage = lazy(() => import("@/pages/sessions/SessionChatPage").then((module) => ({ default: module.SessionChatPage })));
const ToolsPage = lazy(() => import("@/pages/tools/ToolsPage").then((module) => ({ default: module.ToolsPage })));
const KnowledgePage = lazy(() => import("@/pages/knowledge/KnowledgePage").then((module) => ({ default: module.KnowledgePage })));
const TeamsPage = lazy(() => import("@/pages/teams/TeamsPage").then((module) => ({ default: module.TeamsPage })));
const SkillsPage = lazy(() => import("@/pages/skills/SkillsPage").then((module) => ({ default: module.SkillsPage })));
const ModelProvidersPage = lazy(() => import("@/pages/models/ModelProvidersPage").then((module) => ({ default: module.ModelProvidersPage })));
const SettingsPage = lazy(() => import("@/pages/settings/SettingsPage").then((module) => ({ default: module.SettingsPage })));

export default function App() {
  const { t } = useTranslation();
  return (
    <>
      <ThemeSync />
      <LanguageSync />
      <RoutePreloader />
      <ErrorBoundary>
        <Suspense fallback={<LoadingSpinner label={t("app.loadingStudio")} />}>
          <Routes>
            <Route path="/login" element={<LoginPage />} />
            <Route path="/" element={<Navigate to="/dashboard" replace />} />
            <Route
              element={
                <ProtectedRoute>
                  <AppLayout />
                </ProtectedRoute>
              }
            >
              <Route path="/dashboard" element={<DashboardPage />} />
              <Route path="/agents" element={<AgentListPage />} />
              <Route path="/sessions" element={<SessionChatPage />} />
              <Route path="/tools" element={<ToolsPage />} />
              <Route path="/knowledge" element={<KnowledgePage />} />
              <Route path="/knowledge/:section" element={<KnowledgePage />} />
              <Route path="/teams" element={<TeamsPage />} />
              <Route path="/skills" element={<SkillsPage />} />
              <Route path="/models" element={<ModelProvidersPage />} />
              <Route path="/settings" element={<SettingsPage />} />
            </Route>
            <Route path="*" element={<Navigate to="/dashboard" replace />} />
          </Routes>
        </Suspense>
      </ErrorBoundary>
      <Toaster />
    </>
  );
}

function ThemeSync() {
  const theme = useUiStore((state) => state.theme);
  useEffect(() => {
    document.documentElement.classList.toggle("dark", theme === "dark");
  }, [theme]);
  return null;
}

function RoutePreloader() {
  useEffect(() => {
    const preload = () => {
      void Promise.all([
        import("@/pages/dashboard/DashboardPage"),
        import("@/pages/agents/AgentListPage"),
        import("@/pages/sessions/SessionChatPage"),
        import("@/pages/tools/ToolsPage"),
        import("@/pages/knowledge/KnowledgePage"),
        import("@/pages/teams/TeamsPage"),
        import("@/pages/skills/SkillsPage"),
        import("@/pages/models/ModelProvidersPage"),
        import("@/pages/settings/SettingsPage"),
      ]);
    };
    const requestIdle = window.requestIdleCallback ?? ((callback: IdleRequestCallback) => window.setTimeout(callback, 400));
    const cancelIdle = window.cancelIdleCallback ?? window.clearTimeout;
    const handle = requestIdle(preload);
    return () => cancelIdle(handle);
  }, []);
  return null;
}

function LanguageSync() {
  const language = useUiStore((state) => state.language);
  useEffect(() => {
    if (language && i18n.language !== language) {
      i18n.changeLanguage(language);
    }
  }, [language]);
  return null;
}
