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

import { Suspense } from 'react'
import { Await } from 'react-router'
import { MeiliSearchFilterBuilder } from 'meilisearch-helper'

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: 'Histórico de compras' }]
}

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

  let builder = new MeiliSearchFilterBuilder().where('tenant_id', '=', orgid)

  const orders = createSearch({
    index: 'betaeducacao-prod-orders',
    filter: builder.build(),
    sort: [sort],
    query,
    page,
    hitsPerPage,
    env: context.cloudflare.env
  })

  return {
    data: orders
  }
}

export default function Route({ loaderData: { data } }: Route.ComponentProps) {
  return (
    <Suspense fallback={<Skeleton />}>
      <div className="space-y-0.5 mb-8">
        <h1 className="text-2xl font-bold tracking-tight">
          Histórico de pagamentos
        </h1>
        <p className="text-muted-foreground">
          Acompanhe todos as compras realizadas, visualize pagamentos e mantenha
          o controle financeiro.
        </p>
      </div>

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