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'
import { Container } from '~/components/container'

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 />}
    </>
  )
}

function Loading() {
  return (
    <Container>
      <div className="animate-pulse flex flex-col gap-2.5 lg:w-2/4 [&>*]:bg-gray-200 dark:[&>*]:bg-gray-700 [&>*]:h-5 [&>*]:rounded-md">
        <div className="w-2/6" />
        <div className="w-4/6" />
        <div className="w-5/6" />
        <div className="w-5/6" />
        <div className="w-6/6" />
        <div className="w-6/6" />
        <div className="w-3/6" />
        <div className="w-5/6" />
        <div className="w-4/6" />
        <div className="w-4/6" />
      </div>
    </Container>
  )
}
