import { useNavigation, redirect, useNavigate } from 'react-router'
import { fetchAuthSession } from 'aws-amplify/auth'
import { Link } from 'react-router'
import { Outlet } from 'react-router'
import { useAuth } from '~/hooks/use-auth'

export async function clientLoader() {
  const session = await fetchAuthSession()

  if (!session?.tokens?.idToken) {
    throw redirect('/auth')
  }
}

export default function Layout() {
  const navigation = useNavigation()
  const navigate = useNavigate()
  const { signOut } = useAuth()
  const isNavigating = Boolean(navigation.location)

  return (
    <>
      <nav>
        <ul className="flex gap-1">
          <li>
            <Link to="/orders">Pagamentos</Link>
          </li>
          <li>
            <Link to="/users">Usuários</Link>
          </li>
          <li>
            <Link to="/enrollments">Matrículas</Link>
          </li>
        </ul>

        <button
          onClick={() => {
            signOut()
            navigate('/auth')
          }}
        >
          Sair
        </button>
      </nav>

      {isNavigating ? <>Loading...</> : <Outlet />}
    </>
  )
}
