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

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

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

import { MeiliSearchFilterBuilder } from 'meilisearch-helper'
import { columns, type Order } from './columns'

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

export async function loader({ context, request }: Route.LoaderArgs) {
  const cloudflare = context.get(cloudflareContext)
  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

  let builder = new MeiliSearchFilterBuilder().where(
    'test_mode',
    'exists',
    false
  )
  const payments = createSearch({
    index: 'betaeducacao-prod-orders',
    filter: builder.build(),
    sort: [sort],
    page,
    hitsPerPage,
    env: cloudflare.env
  })

  return { payments }
}

export default function Route({
  loaderData: { payments }
}: Route.ComponentProps) {
  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={payments}>
        {({ hits, page = 1, hitsPerPage, totalHits }) => {
          return (
            <DataTable
              sort={[{ id: 'created_at', desc: true }]}
              columnPinning={{ left: ['select'], right: ['action'] }}
              columns={columns}
              data={hits as Order[]}
              pageIndex={page - 1}
              pageSize={hitsPerPage}
              rowCount={totalHits}
            />
          )
        }}
      </Await>
    </Suspense>
  )
}
