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

import type { TCategories } from '~/apis/admin/get-news'
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.contents'
import { formatDate } from '~/utils/formatter'

export const ContentsPage = () => {
  const loaderData = useRouteLoaderData<typeof loader>(
    'routes/_admin.lg-admin._dashboard.contents',
  )
  const newsData = loaderData?.newsData

  DataTable.use(DT)
  const dataTable = newsData
  const dataColumns = [
    {
      title: 'No',
      data: undefined,
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      render: function (data: any, type: any, row: any, meta: any) {
        return meta.row + 1
      },
    },
    { title: 'Tanggal Konten', data: 'live_at' },
    {
      title: 'Nama Penulis',

      data: 'author',
    },
    { title: 'Judul', data: 'title' },
    { title: 'Kategori', data: 'categories' },
    {
      title: 'Tags',
      data: 'is_premium',
      render: (value: string) => {
        return value
          ? `<span class="bg-[#FFFCAF] text-[#DBCA6E] px-4 py-2 rounded-full">Premium</span>`
          : `<span class="bg-[#F5F5F5] text-[#4C5CA0] px-4 py-2 rounded-full">Normal</span>`
      },
    },
    {
      title: 'Action',
      data: 'slug',
    },
  ]
  const dataSlot = {
    1: (value: string) => {
      return formatDate(value)
    },
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    2: (value: any, type: any, data: any) =>
      `<span>${value.name}</span> <br> <span class="text-sm text-[#7C7C7C]">ID: ${data.id.slice(0, 12)}</span>`,
    4: (value: TCategories) => {
      const categories = value.map((item) => item.name).join(', ')
      return `${categories}`
    },
    6: (value: string | number) => {
      return (
        <Button
          as="a"
          href={`/lg-admin/contents/update/${value}`}
          className="text-md rounded-md"
          size="sm"
        >
          Lihat Detail
        </Button>
      )
    },
  }
  const dataOptions = {
    paging: true,
    searching: true,
    ordering: true,
    info: true,
  }

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

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