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 {
  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="/" element={<Layout />}>
                <Route index element={<Navigate to="/templates" replace />} />
                <Route path="templates/" element={<TemplatesOverviewPage />} />
                <Route
                  path="templates/:templateId/edit"
                  element={<TemplateEditPage />}
                />
                <Route
                  path="templates/:templateId/elements"
                  element={<ElementsCreation />}
                />
                <Route
                  path="templates/:templateId/protocols"
                  element={<ProtocolCreation />}
                />
                <Route
                  path="standards-management"
                  element={<StandardsManagementPage />}
                />
              </Route>
            </Routes>
          </TemplateProvider>
        </CategoryProvider>
      </ToastProvider>
    </QueryClientProvider>
  )
}

export default App
