import { createContext, useContext } from 'react'
import { Navigate } from '@tanstack/react-router'
import { Container, Text } from '@pikku/mantine/core'
import { m } from '@/i18n/messages'
import { useLocale } from '@/i18n/config'
import { usePikkuQuery } from '@project/functions-sdk/pikku/api.gen'
import { AppLayout } from './components/AppLayout'

type Me = ReturnType<typeof usePikkuQuery<'me'>>['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({
  roles,
  children,
}: {
  roles?: Array<'client' | 'admin' | 'owner'>
  children: React.ReactNode
}) {
  useLocale()
  const { data, isLoading, error } = usePikkuQuery('me', null, {
    retry: false,
  })

  if (isLoading) {
    return <Container py="xl"><Text>{m.common__states__loading()}</Text></Container>
  }
  if (error || !data) {
    return <Navigate to="/login" />
  }
  if (roles && !roles.includes(data.role as 'client' | 'admin' | 'owner')) {
    return <Navigate to="/" />
  }
  return (
    <AuthContext.Provider value={data}>
      <AppLayout user={data}>{children}</AppLayout>
    </AuthContext.Provider>
  )
}
