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

import type { TUserResponse } from '~/apis/admin/get-users'
import { getStatusBadge, type TColorBadge } from '~/components/ui/color-badge'
import { UiTable } from '~/components/ui/table'
import { TitleDashboard } from '~/components/ui/title-dashboard'
import type { loader } from '~/routes/_admin.lg-admin._dashboard.users._index'
import { formatDate } from '~/utils/formatter'

export const UsersPage = () => {
  const loaderData = useRouteLoaderData<typeof loader>(
    'routes/_admin.lg-admin._dashboard.users._index',
  )

  DataTable.use(DT)
  const dataTable =
    loaderData?.usersData?.sort(
      (a, b) =>
        new Date(b.subscribe.start_date).getTime() -
        new Date(a.subscribe.start_date).getTime(),
    ) || []

  const dataColumns: ConfigColumns[] = [
    {
      title: 'No',
      render: (
        _data: unknown,
        _type: unknown,
        _row: unknown,
        meta: { row: number },
      ) => {
        return meta.row + 1
      },
    },
    {
      title: 'Tanggal Daftar',
      data: 'subscribe.start_date',
    },
    {
      title: 'Nama User',
    },
    {
      title: 'Email',
      data: 'email',
    },
    {
      title: 'Status',
      data: 'subscribe.subscribe_plan.name',
    },
  ]
  const dataSlot: DataTableSlots = {
    1: (value: string) => formatDate(value),
    2: (_value: unknown, _type: unknown, data: TUserResponse) => (
      <div>
        <div>{data.phone}</div>
        <div className="text-sm text-[#7C7C7C]">ID: {data.id.slice(0, 8)}</div>
      </div>
    ),
    4: (value: TColorBadge, _type: unknown, data: TUserResponse) => (
      <span
        className={`rounded-lg px-2 text-sm ${getStatusBadge(data.subscribe.status as TColorBadge)}`}
      >
        {value}
      </span>
    ),
  }

  return (
    <div className="relative">
      <TitleDashboard title="Users" />

      <div className="mb-8 flex items-end justify-between gap-5">
        <div className="flex-1">{/* TODO: Filter */}</div>
      </div>

      <UiTable
        data={dataTable || []}
        columns={dataColumns}
        slots={dataSlot}
        title="Daftar Users"
      />
    </div>
  )
}
