import { createContext, useContext } from 'react'
import { Navigate } from '@tanstack/react-router'
import { Center, Loader } from '@pikku/mantine/core'
import { usePikkuQuery } from '@germantax/functions-sdk/pikku/api.gen'
import { AppLayout } from './components/AppLayout'

type Me = ReturnType<typeof usePikkuQuery<'getMe'>>['data']

const AuthContext = createContext<Me | null>(null)

export function useAuth(): NonNullable<Me> {
  const ctx = useContext(AuthContext)
  if (!ctx) {
    throw new Error('useAuth must be used inside <RequireAuth>')
  }
  return ctx
}

export function RequireAuth({ children }: { children: React.ReactNode }) {
  const { data, isLoading, error } = usePikkuQuery('getMe', undefined as never, {
    retry: false,
  })

  if (isLoading) {
    return (
      <Center mih="100vh">
        <Loader size="sm" />
      </Center>
    )
  }
  if (error || !data) {
    return <Navigate to="/login" />
  }
  return (
    <AuthContext.Provider value={data}>
      <AppLayout user={data}>{children}</AppLayout>
    </AuthContext.Provider>
  )
}
