import DT from 'datatables.net-dt'
import DataTable from 'datatables.net-react'
import { Link, useRouteLoaderData } from 'react-router'

import type { TCategoryResponse } from '~/apis/common/get-categories'
import { Button } from '~/components/ui/button'
import { UiTable } from '~/components/ui/table'
import { TitleDashboard } from '~/components/ui/title-dashboard'
import type { loader } from '~/routes/_admin.lg-admin._dashboard.categories._index'
export const CategoriesPage = () => {
  const loaderData = useRouteLoaderData<typeof loader>(
    'routes/_admin.lg-admin._dashboard.categories._index',
  )
  const { dataCategories: categoriesData } = loaderData || {}

  DataTable.use(DT)
  const dataTable = categoriesData?.sort((a, b) => {
    if (a.sequence === null) return 1
    if (b.sequence === null) return -1
    return a.sequence - b.sequence
  })
  const dataColumns = [
    {
      title: 'No',
      render: (
        data: unknown,
        type: unknown,
        row: TCategoryResponse,
        meta: { row: number },
      ) => {
        return `<div>${meta.row + 1}</div> ${
          row.sequence === null
            ? ''
            : `<pre class="text-sm text-[#7C7C7C] inline">Urutan: ${row.sequence}</pre>`
        }`
      },
    },
    {
      title: 'Kategori',
    },
    {
      title: 'Deskripsi',
      data: 'description',
    },
    {
      title: 'Action',
      data: 'id',
    },
  ]
  const dataSlot = {
    1: (_value: unknown, _type: unknown, data: TCategoryResponse) => (
      <div>
        <div>{data.name}</div>
        <pre className="text-sm text-[#7C7C7C]">Kode: {data.code}</pre>
      </div>
    ),
    3: (value: string) => (
      <Button
        as="a"
        href={`/lg-admin/categories/update/${value}`}
        className="text-md rounded-md"
        size="sm"
      >
        Update Kategori
      </Button>
    ),
  }
  const dataOptions = {
    paging: true,
    searching: true,
    ordering: true,
    info: true,
  }

  return (
    <div className="relative">
      <TitleDashboard title="Kategori" />
      <div className="mb-8 flex items-end justify-between gap-5">
        <div className="flex-1">{/* TODO: Filter */}</div>
        <Button
          as={Link}
          to="/lg-admin/categories/create"
          className="text-md h-[42px] rounded-md"
          size="lg"
        >
          Buat Kategori
        </Button>
      </div>

      <UiTable
        data={dataTable}
        columns={dataColumns}
        options={dataOptions}
        slots={dataSlot}
        title="Daftar Kategori"
      />
    </div>
  )
}
