import { useEffect, useState } from 'react'
import { HeadContent, Outlet, Scripts, createRootRoute } from '@tanstack/react-router'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MantineProvider } from '@pikku/mantine/core'
import { PikkuProvider, createPikku } from '@pikku/react'
import '@mantine/core/styles.css'
import { PikkuFetch } from '@germantax/functions-sdk/pikku/pikku-fetch.gen'
import { PikkuRPC } from '@germantax/functions-sdk/pikku/pikku-rpc.gen'
import { theme } from '@germantax/mantine-theme'
import '../theme.css'
import '../i18n/config'

declare global {
  interface Window {
    __E2E_API_URL?: string
  }
}

export const Route = createRootRoute({
  head: () => ({
    meta: [
      { charSet: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { title: 'GmbH Resolution Manager' },
    ],
  }),
  component: RootDocument,
})

function RootDocument() {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 10_000,
            retry: 1,
            refetchOnWindowFocus: false,
          },
          mutations: { retry: 0 },
        },
      }),
  )
  const runtimeApiUrl =
    typeof window !== 'undefined' ? window.__E2E_API_URL : undefined
  const [pikku] = useState(() =>
    createPikku(PikkuFetch, PikkuRPC, {
      serverUrl: runtimeApiUrl ?? import.meta.env.VITE_API_URL ?? '/api',
      credentials: 'include',
    }),
  )

  return (
    <html lang="de" data-app-hydrated="false">
      <head>
        <HeadContent />
      </head>
      <body>
        <QueryClientProvider client={queryClient}>
          <MantineProvider theme={theme}>
            <PikkuProvider pikku={pikku}>
              <HydrationReady />
              <Outlet />
            </PikkuProvider>
          </MantineProvider>
        </QueryClientProvider>
        <Scripts />
      </body>
    </html>
  )
}

function HydrationReady() {
  useEffect(() => {
    window.document.documentElement.dataset.appHydrated = 'true'
  }, [])
  return null
}
