import { FC, useEffect } from 'react'

import { Navigate, Route, Routes } from 'react-router-dom'

import Layout from '@/app/Layout'
import { CategoryProvider } from '@/entity/template/model/CategoryContext'
import { TemplateProvider } from '@/entity/template/model/TemplateContext'
import {
  setGlobalToastContext,
  ToastProvider,
  useToast,
} from '@/lib/hooks/useToast'
import AdminGuard from '@/feature/auth/AdminGuard'
import LoginPage from '@/feature/auth/LoginPage'
import {
  ElementsCreation,
  ProtocolCreation,
  StandardsManagementPage,
  TemplateEditPage,
  TemplatesOverviewPage,
} from '@/page'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const queryClient = new QueryClient()

// Компонент для инициализации глобального контекста toast
const ToastInitializer: FC = () => {
  const toast = useToast()

  useEffect(() => {
    setGlobalToastContext(toast)
  }, [toast])

  return null
}

const App: FC = () => {
  return (
    <QueryClientProvider client={queryClient}>
      <ToastProvider>
        <ToastInitializer />
        <CategoryProvider>
          <TemplateProvider>
            <Routes>
              <Route path="/login" element={<LoginPage />} />
              <Route path="/" element={<Layout />}>
                <Route index element={<Navigate to="/templates" replace />} />
                <Route path="templates/" element={<TemplatesOverviewPage />} />
                <Route
                  path="templates/:templateId/edit"
                  element={<AdminGuard><TemplateEditPage /></AdminGuard>}
                />
                <Route
                  path="templates/:templateId/elements"
                  element={<AdminGuard><ElementsCreation /></AdminGuard>}
                />
                <Route
                  path="templates/:templateId/protocols"
                  element={<ProtocolCreation />}
                />
                <Route
                  path="standards-management"
                  element={<StandardsManagementPage />}
                />
              </Route>
            </Routes>
          </TemplateProvider>
        </CategoryProvider>
      </ToastProvider>
    </QueryClientProvider>
  )
}

export default App
