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

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

import { DataTable } from '@repo/ui/components/data-table'
import { Skeleton } from '@repo/ui/components/skeleton'
import { createSearch } from '@repo/util/meili'

import { columns, type Order } from './columns'

export function meta({}: Route.MetaArgs) {
  return [{ title: 'Pagamentos' }]
}

export async function loader({ context, request }: Route.LoaderArgs) {
  const { searchParams } = new URL(request.url)
  const page = Number(searchParams.get('p')) + 1
  const sort = searchParams.get('sort') || 'create_date:desc'
  const hitsPerPage = Number(searchParams.get('perPage')) || 25

  return {
    data: createSearch({
      index: 'betaeducacao-prod-orders',
      sort: [sort],
      page,
      hitsPerPage,
      env: context.cloudflare.env
    })
  }
}

export default function Route({ loaderData: { data } }) {
  return (
    <Suspense fallback={<Skeleton />}>
      <div className="space-y-0.5 mb-8">
        <h1 className="text-2xl font-bold tracking-tight">Pagamentos</h1>
      </div>

      <Await resolve={data}>
        {({ hits, page, hitsPerPage, totalHits }) => {
          return (
            <DataTable
              sort={[{ id: 'created_at', desc: true }]}
              columns={columns}
              data={hits as Order[]}
              pageIndex={page - 1}
              pageSize={hitsPerPage}
              rowCount={totalHits}
            />
          )
        }}
      </Await>
    </Suspense>
  )
}
