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

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

import { type User } from '@repo/auth/auth'
import { userContext } from '@repo/auth/context'
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator
} from '@repo/ui/components/ui/breadcrumb'
import { createSearch } from '@repo/util/meili'
import { Skeleton } from '@repo/ui/components/skeleton'
import { DataTable } from '@repo/ui/components/data-table'
import { columns, type Order } from '@repo/ui/routes/orders/columns'

import { Container } from '@/components/container'

export function meta({}: Route.MetaArgs) {
  return [{ title: 'Histórico de compras' }]
}

export async function loader({ request, context }: Route.ActionArgs) {
  const user = context.get(userContext) as User
  const { searchParams } = new URL(request.url)
  const status = searchParams.getAll('status') || []
  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('user_id', '=', user.sub)

  if (status.length) {
    builder = builder.where('status', 'in', status)
  }

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

  return {
    data: payments
  }
}

export default function Component({ loaderData: { data } }) {
  return (
    <Container className="space-y-2.5">
      <Suspense fallback={<Skeleton />}>
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link to="..">Meus cursos</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>Histórico de pagamentos</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        <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>
    </Container>
  )
}
