import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useAuthStore } from './lib/store'
import { useEffect, Suspense, lazy } from 'react'
import { ThemeProvider } from './contexts/ThemeContext'
import LoadingSpinner from './components/common/LoadingSpinner'
import PasscodeGuard from './components/common/PasscodeGuard'

// Layout
import Layout from './components/layout/Layout'

// Lazy load pages
const Dashboard = lazy(() => import('./pages/Dashboard'))
const Templates = lazy(() => import('./pages/Templates'))
const TemplateCreate = lazy(() => import('./pages/TemplateCreate'))
const TemplateEdit = lazy(() => import('./pages/TemplateEdit'))
const TopicosGestao = lazy(() => import('./pages/TopicosGestao'))
const Databooks = lazy(() => import('./pages/Databooks'))
const DatabookNew = lazy(() => import('./pages/DatabookNew'))
const DatabookEdit = lazy(() => import('./pages/DatabookEdit'))
const DatabookView = lazy(() => import('./pages/DatabookView'))
const Configuracoes = lazy(() => import('./pages/Configuracoes'))
const Busca = lazy(() => import('./pages/Busca'))
const DesignDatabook = lazy(() => import('./pages/DesignDatabook'))

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutos
      gcTime: 1000 * 60 * 10, // 10 minutos (antes era cacheTime)
      retry: 1,
      refetchOnWindowFocus: false,
    },
    mutations: {
      retry: 1,
    },
  },
})

// Bypassing Auth for development phase
function App() {
  const setUser = useAuthStore((state) => state.setUser)

  // Opcional: manter uma sessão "fantasma" do admin fixo enquanto o login está desativado
  useEffect(() => {
    // Definimos um usuário fake para não quebrar componentes que dependem de useAuthStore
    setUser({ id: 'dev-user', email: 'admin@tracksteel.com.br' } as any)
  }, [setUser])

  return (
    <ThemeProvider>
      <PasscodeGuard>
        <QueryClientProvider client={queryClient}>
          <BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
            <Suspense fallback={<div className="flex items-center justify-center h-screen"><LoadingSpinner size="lg" /></div>}>
              <Routes>
                {/* Redirecionamos tudo para o dashboard diretamente */}
                <Route path="/login" element={<Navigate to="/" replace />} />
                
                <Route
                  path="/"
                  element={
                    <Layout />
                  }
                >
                  <Route index element={<Navigate to="/dashboard" replace />} />
                  <Route path="dashboard" element={<Dashboard />} />
                  <Route path="templates" element={<Templates />} />
                  <Route path="templates/criar" element={<TemplateCreate />} />
                  <Route path="templates/:id/editar" element={<TemplateEdit />} />
                  <Route path="topicos" element={<TopicosGestao />} />
                  <Route path="databooks" element={<Databooks />} />
                  <Route path="databook/novo" element={<DatabookNew />} />
                  <Route path="databook/:id/editar" element={<DatabookEdit />} />
                  <Route path="databook/:id" element={<DatabookView />} />
                  <Route path="design" element={<DesignDatabook />} />
                  <Route path="configuracoes" element={<Configuracoes />} />
                  <Route path="busca" element={<Busca />} />
                </Route>
              </Routes>
            </Suspense>
          </BrowserRouter>
        </QueryClientProvider>
      </PasscodeGuard>
    </ThemeProvider>
  )
}

export default App
