"use client"

import { signIn, signOut, useSession } from "next-auth/react"
import { useEffect, useState } from "react"
import { useLocalStorage } from "usehooks-ts"

export function SessionRefresher() {
  useSilentAuth()
  useHandleRefreshError()

  return null
}

function useHandleRefreshError() {
  const session = useSession()

  if (session.data?.error === "RefreshAccessTokenError") {
    signOut({ redirect: false })
  }
}

const SILENT_AUTH_KEY = "silent-auth"
const SILENT_AUTH_EXPIRY = 6 * 60 * 1000 // 6 hours

function useSilentAuth() {
  const { status } = useSession()
  const [silentAuthTimestamp, setSilentAuthTimestamp] = useLocalStorage<
    string | undefined
  >(SILENT_AUTH_KEY, undefined)
  const [isLoading, setLoading] = useState(() => status === "unauthenticated")

  const hasCompletedSilentSignin =
    !!silentAuthTimestamp &&
    Date.now() - Number(silentAuthTimestamp) < SILENT_AUTH_EXPIRY

  useEffect(() => {
    if (status !== "unauthenticated") return
    if (hasCompletedSilentSignin) return

    setLoading(true)

    try {
      signIn(
        "sas",
        {},
        {
          prompt: "none",
        }
      )
    } finally {
      setSilentAuthTimestamp(Date.now().toString())
      setLoading(false)
    }
  }, [hasCompletedSilentSignin, setSilentAuthTimestamp, status])

  return { isLoading: status !== "authenticated" && isLoading }
}
