import { useMemo, useState } from 'react'

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

import { getSysFiles } from '@/api'
import { hasPermission } from '@/lib'
import type { SysFile } from '@/schemas'

import { createColumns } from './components/columns.tsx'
import { CrudProvider } from './components/crud-provider.tsx'
import { FileTable } from './components/file-table.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: () =>
      getSysFiles({
        page: pagination.pageIndex + 1,
        page_size: pagination.pageSize,
      }),
    placeholderData: (prev) => prev,
    enabled: hasPermission('file:list'),
  })

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

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

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

  return (
    <CrudProvider>
      <FileTable table={table} />
    </CrudProvider>
  )
}
