import { useMemo, useState } from 'react'

import { useQuery } from '@tanstack/react-query'
import { getCoreRowModel, useReactTable } from '@tanstack/react-table'

import { getCategories } from '@/api'
import { hasPermission } from '@/lib'
import { type Category } from '@/schemas'

import { ActionDialogs } from './components/action-dialogs.tsx'
import { CategoryTable } from './components/category-table.tsx'
import { createColumns } from './components/columns.tsx'
import { CrudProvider } from './components/crud-provider.tsx'
import { QUERY_KEY } from './constants.ts'

export default function CrudPage() {
  const [pagination, setPagination] = useState({
    pageIndex: 0,
    pageSize: 10,
  })

  const { data, isFetching, refetch } = useQuery({
    queryKey: [QUERY_KEY, pagination.pageIndex, pagination.pageSize],
    queryFn: () =>
      getCategories({
        page: pagination.pageIndex + 1,
        page_size: pagination.pageSize,
      }),
    placeholderData: (prev) => prev,
    enabled: hasPermission('category:list'),
  })

  const tableData = useMemo<Category[]>(() => data?.list ?? [], [data])

  const columns = useMemo(() => createColumns(), [])

  const table = useReactTable<Category>({
    data: tableData,
    columns,
    getCoreRowModel: getCoreRowModel(),
    manualPagination: true,
    rowCount: data?.total,
    state: { pagination },
    onPaginationChange: setPagination,
    meta: {
      isFetching,
      refetch,
    },
  })

  return (
    <CrudProvider>
      <ActionDialogs />

      <CategoryTable table={table} />
    </CrudProvider>
  )
}
