import { Await } from 'react-router'

import type { Route } from './+types'

import { Skeleton } from '@/components/skeleton'
import { request as req } from '@/lib/request'
import { Suspense } from 'react'

export async function loader({ params, request, context }: Route.LoaderArgs) {
  const { id } = params
  const r = req({
    url: `/users/${id}/orgs`,
    request,
    context
  }).then((r) => r.json())

  return { data: r }
}

export default function Route({ loaderData: { data } }) {
  return (
    <Suspense fallback={<Skeleton />}>
      <Await resolve={data}>
        {({ items = [] }) => (
          <ul>
            {items.map(
              ({ name, cnpj }: { name: string; cnpj: string }, idx: number) => {
                return (
                  <li key={idx}>
                    {name} {cnpj}
                  </li>
                )
              }
            )}
          </ul>
        )}
      </Await>
    </Suspense>
  )
}
