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

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

import { DataTable } from '@repo/ui/components/data-table'
import { SearchForm } from '@repo/ui/components/search-form'
import { Skeleton } from '@repo/ui/components/skeleton'
import { Kbd } from '@repo/ui/components/ui/kbd'
import { createSearch } from '@repo/util/meili'

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

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

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

  const orgs = createSearch({
    index: 'betaeducacao-prod-users_d2o3r5gmm4it7j',
    sort: ['createDate:desc', 'create_date:desc'],
    filter: 'cnpj EXISTS',
    query,
    page,
    hitsPerPage,
    env: context.cloudflare.env
  })

  return { data: orgs }
}

export default function Route({ loaderData: { data } }: Route.ComponentProps) {
  const [searchParams, setSearchParams] = useSearchParams()

  return (
    <Suspense fallback={<Skeleton />}>
      <div className="space-y-0.5 mb-8">
        <h1 className="text-2xl font-bold tracking-tight">Empresas</h1>
      </div>

      <Await resolve={data}>
        {({ hits, page, hitsPerPage, totalHits }) => {
          return (
            <DataTable
              sort={[{ id: 'created_at', desc: true }]}
              columnPinning={{ left: ['select'], right: ['action'] }}
              columns={columns}
              data={hits as Org[]}
              pageIndex={page - 1}
              pageSize={hitsPerPage}
              rowCount={totalHits}
            >
              <div className="flex flex-col lg:flex-row justify-between gap-2.5 mb-2.5">
                <div className="2xl:w-1/4">
                  <SearchForm
                    placeholder={
                      <>
                        Digite <Kbd className="border font-mono">/</Kbd> para
                        pesquisar
                      </>
                    }
                    defaultValue={searchParams.get('q') || ''}
                    onChange={(value) =>
                      setSearchParams((searchParams) => {
                        searchParams.set('q', String(value))
                        searchParams.delete('p')
                        return searchParams
                      })
                    }
                  />
                </div>
              </div>
            </DataTable>
          )
        }}
      </Await>
    </Suspense>
  )
}
