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

import { Suspense } from 'react'
import { Await } from 'react-router'

import { request as req } from '@/lib/request'
import { Skeleton } from '@repo/ui/components/skeleton'

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

  return { data }
}

export default function Route({ loaderData: { data } }) {
  return (
    <Suspense fallback={<Skeleton />}>
      <Await resolve={data}>
        {({ items = [] }) => (
          <ul>
            {items.map(({ sk }: { sk: string }, idx: number) => {
              const [, email] = sk.split('#')
              return <li key={idx}>{email}</li>
            })}
          </ul>
        )}
      </Await>
    </Suspense>
  )
}
