import type { QueryClient } from '@tanstack/react-query'
import { useSuspenseQuery } from '@tanstack/react-query'
import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'
import { lazy, Suspense } from 'react'
import { Helmet } from 'react-helmet-async'
import { ErrorState } from '~/components/error-state'
import { Shell } from '~/components/layout/shell'
import { NotFound } from '~/components/not-found'
import { globalsQuery, menusQuery } from '~/lib/queries'

const TanStackRouterDevtools = import.meta.env.PROD
  ? () => null
  : lazy(() => import('@tanstack/react-router-devtools').then((m) => ({ default: m.TanStackRouterDevtools })))

const ReactQueryDevtools = import.meta.env.PROD
  ? () => null
  : lazy(() => import('@tanstack/react-query-devtools').then((m) => ({ default: m.ReactQueryDevtools })))

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  loader: async ({ context: { queryClient } }) => {
    await Promise.all([queryClient.ensureQueryData(globalsQuery), queryClient.ensureQueryData(menusQuery)])
  },
  component: RootComponent,
  notFoundComponent: () => (
    <Shell>
      <NotFound />
    </Shell>
  ),
  errorComponent: ({ error, reset }) => (
    <Shell>
      <ErrorState error={error} reset={reset} />
    </Shell>
  ),
})

function RootComponent() {
  const { data: globals } = useSuspenseQuery(globalsQuery)
  return (
    <>
      <Helmet defaultTitle={globals.meta_title} titleTemplate={`%s — ${globals.meta_title}`}>
        <meta name="description" content={globals.meta_description} />
      </Helmet>
      <Shell>
        <Outlet />
      </Shell>
      <Suspense>
        <TanStackRouterDevtools />
        <ReactQueryDevtools buttonPosition="bottom-left" />
      </Suspense>
    </>
  )
}
