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

import { PlusIcon } from 'lucide-react'
import { Suspense, useState } from 'react'
import { Await, Link, useParams, useSearchParams } from 'react-router'
import { MeiliSearchFilterBuilder } from 'meilisearch-helper'

import { DataTable } from '@repo/ui/components/data-table'
import { SearchForm } from '@repo/ui/components/search-form'
import { Skeleton } from '@repo/ui/components/skeleton'
import { Button } from '@repo/ui/components/ui/button'
import { Kbd } from '@repo/ui/components/ui/kbd'
import { ExportMenu } from '@repo/ui/components/export-menu'
import { createSearch } from '@repo/util/meili'
import { headers } from '@repo/ui/routes/users/data'

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 sort = searchParams.get('sort') || 'createDate:desc'
  const page = Number(searchParams.get('p')) + 1
  const hitsPerPage = Number(searchParams.get('perPage')) || 25

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

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

  return { data: users }
}

export default function Route({ loaderData: { data } }: Route.ComponentProps) {
  const { orgid } = useParams()
  const [searchParams, setSearchParams] = useSearchParams()
  const [selectedRows, setSelectedRows] = useState<User[]>([])

  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
              sort={[{ id: 'createDate', desc: true }]}
              columns={columns}
              data={hits as User[]}
              pageIndex={page - 1}
              pageSize={hitsPerPage}
              rowCount={totalHits}
              setSelectedRows={setSelectedRows}
            >
              <div className="flex max-lg:flex-col gap-2.5 mb-2.5">
                {selectedRows.length ? (
                  <>
                    <div className="flex gap-2.5 items-center">
                      <ExportMenu
                        name={`${orgid}_users`}
                        headers={headers}
                        selectedRows={selectedRows}
                      />
                    </div>
                  </>
                ) : (
                  <>
                    <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>

                    <Button className="lg:ml-auto" asChild>
                      <Link to="add">
                        <PlusIcon /> Adicionar
                      </Link>
                    </Button>
                  </>
                )}
              </div>
            </DataTable>
          )
        }}
      </Await>
    </Suspense>
  )
}
