import { Href, useRouter } from 'expo-router'
import { useRouteInfo } from 'expo-router/build/hooks'
import { ReactNode, useEffect } from 'react'
import { useAuth, useAuthLogin } from '@/hooks/useAuth'
import * as SecureStore from '@/utils/SecureStore'

type Props = {
  loginRedirect: Href
  children: ReactNode
}

export default function LoginProvider({ loginRedirect, children }: Props) {
  const router = useRouter()
  const route = useRouteInfo()
  const auth = useAuth()
  const authLogin = useAuthLogin()

  // Renouvellement auto du jeton d'authentification
  useEffect(() => {
    const { name, token } = auth
    const password = SecureStore.getItem('apiPassword')
    if (name === null || (password === null && token === null))
      return
    let waitTime = 0
    if (token !== null && token !== undefined) {
      const arrayToken = token.split('.')
      const tokenPayload = JSON.parse(atob(arrayToken[1]))
      const expTime: number = tokenPayload.exp * 1000
      const now: number = Math.floor(new Date().getTime())
      waitTime = expTime - now
    }
    const timeout = setTimeout(async () => {
      const password = SecureStore.getItem('apiPassword')
      if (password) {
        await fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/auth/login/`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ name: name, password: password })
        })
        .then(resp => resp.json())
        .then(resp => {
          if (!resp.error)
            authLogin({ name: name, token: resp.accessToken })
          else
            authLogin({ name: name, token: null })
        })
      }
      else {
        authLogin({ name: name, token: null })
      }
    }, waitTime)
    return () => clearTimeout(timeout)
  }, [auth])

  // Si on est pas connecté⋅e, on reste sur la fenêtre de connexion
  useEffect(() => {
    if (!auth.loggedIn && route.pathname !== loginRedirect)
      router.navigate(loginRedirect)
  }, [auth, route, router])

  return <>
    {children}
  </>
}