import { useEffect } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth';
import { useAppStore } from '@/stores/app';
import AppShell from '@/components/layout/AppShell';
import LoginPage from '@/pages/LoginPage';
import ChatPage from '@/pages/ChatPage';
import TerraformPage from '@/pages/TerraformPage';
import PromptGeneratorPage from '@/pages/PromptGeneratorPage';
import WorkspacesPage from '@/pages/WorkspacesPage';
import ExplorerPage from '@/pages/ExplorerPage';
import ReportsPage from '@/pages/ReportsPage';
import OciConfigPage from '@/pages/config/OciConfigPage';
import GenAiConfigPage from '@/pages/config/GenAiConfigPage';
import McpServersPage from '@/pages/config/McpServersPage';
import AdbConfigPage from '@/pages/config/AdbConfigPage';
import EmbeddingsPage from '@/pages/config/EmbeddingsPage';
import EmbConsultPage from '@/pages/config/EmbConsultPage';
import UsersPage from '@/pages/admin/UsersPage';
import MfaPage from '@/pages/admin/MfaPage';
import AuditPage from '@/pages/admin/AuditPage';

export default function App() {
  const checkAuth = useAuthStore((s) => s.checkAuth);
  const loadData = useAppStore((s) => s.loadData);
  const user = useAuthStore((s) => s.user);

  useEffect(() => {
    checkAuth().then(() => {
      if (useAuthStore.getState().user) loadData();
    });
  }, [checkAuth, loadData]);

  // Reload data when user changes (login)
  useEffect(() => {
    if (user) loadData();
  }, [user, loadData]);

  return (
    <Routes>
      <Route path="/login" element={<LoginPage />} />
      <Route element={<AppShell />}>
        <Route index element={<Navigate to="/chat" replace />} />
        <Route path="/chat" element={<ChatPage />} />
        <Route path="/terraform" element={<TerraformPage />} />
        <Route path="/terraform/prompt" element={<PromptGeneratorPage />} />
        <Route path="/terraform/workspaces" element={<WorkspacesPage />} />
        <Route path="/explorer" element={<ExplorerPage />} />
        <Route path="/reports" element={<ReportsPage />} />
        <Route path="/config/oci" element={<OciConfigPage />} />
        <Route path="/config/genai" element={<GenAiConfigPage />} />
        <Route path="/config/mcp" element={<McpServersPage />} />
        <Route path="/config/adb" element={<AdbConfigPage />} />
        <Route path="/config/embeddings" element={<EmbeddingsPage />} />
        <Route path="/config/embeddings/consult" element={<EmbConsultPage />} />
        <Route path="/admin/users" element={<UsersPage />} />
        <Route path="/admin/mfa" element={<MfaPage />} />
        <Route path="/admin/audit" element={<AuditPage />} />
      </Route>
      <Route path="*" element={<Navigate to="/chat" replace />} />
    </Routes>
  );
}
