import { useMemo } from 'react'

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

import { getAllSysMenus } from '@/api'
import { generateMenus, hasPermission } from '@/lib'
import { type SysMenuTree } from '@/schemas'

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

export default function CrudPage() {
  const { data, isFetching, refetch } = useQuery({
    queryKey: [QUERY_KEY],
    queryFn: () => getAllSysMenus(),
    placeholderData: (prev) => prev,
    enabled: hasPermission('menu:list'),
  })

  const tableData = useMemo<SysMenuTree[]>(
    () => generateMenus({ menus: data?.data ?? [], showHidden: true, showButton: true }),
    [data],
  )

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

  const table = useReactTable<SysMenuTree>({
    data: tableData,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getExpandedRowModel: getExpandedRowModel(),
    manualPagination: true,
    meta: {
      isFetching,
      refetch,
    },
    getSubRows: (row) => row.children,
  })

  return (
    <CrudProvider>
      <ActionDialogs />
      <MenuTable table={table} />
    </CrudProvider>
  )
}
