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

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

import { DataTable } from '@/components/data-table'
import { SearchForm } from '@/components/search-form'
import { Skeleton } from '@/components/skeleton'
import { createSearch } from '@/lib/meili'
import { Button } from '@repo/ui/components/ui/button'
import { Kbd } from '@repo/ui/components/ui/kbd'
import { columns, type User } from './columns'

export function meta({}: Route.MetaArgs) {
  return [
    { title: 'Colaboradores' },
    {
      name: 'description',
      content: 'Adicione colaboradores e organize sua equipe de forma prática'
    }
  ]
}

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

  const users = createSearch({
    index: 'betaeducacao-prod-users_d2o3r5gmm4it7j',
    sort: ['createDate:desc', 'create_date:desc'],
    filter: `tenant_id = ${orgid}`,
    query,
    page,
    hitsPerPage,
    env: context.cloudflare.env
  })

  return { data: users }
}

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

  return (
    <Suspense fallback={<Skeleton />}>
      <div className="space-y-0.5 mb-8">
        <h1 className="text-2xl font-bold tracking-tight">
          Gerenciar colaboradores
        </h1>
        <p className="text-muted-foreground">
          Adicione colaboradores e organize sua equipe de forma prática.
        </p>
      </div>

      <Await resolve={data}>
        {({ hits, page, hitsPerPage, totalHits }) => {
          return (
            <DataTable
              columns={columns}
              data={hits as User[]}
              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={
                      <>
                        Pressione <Kbd className="border font-mono">/</Kbd> para
                        pesquisar...
                      </>
                    }
                    defaultValue={searchParams.get('q') || ''}
                    onChange={(value) =>
                      setSearchParams((searchParams) => {
                        searchParams.set('q', value)
                        searchParams.delete('p')
                        return searchParams
                      })
                    }
                  />
                </div>
                <Button variant="outline" asChild>
                  <Link to="add">
                    <PlusIcon /> Adicionar colaborador
                  </Link>
                </Button>
              </div>
            </DataTable>
          )
        }}
      </Await>
    </Suspense>
  )
}
