import {Card, Space, Button, Table} from 'antd';
import {FC} from 'react';
import {useHandle, useList} from './hooks';
import {usePage} from '@hooks';
import {pageContext} from '../context';
import {PAGE_SIZE_LIST} from '@utils';
import RoleModal from './modal';
import TreeModal from './tree-modal';

const TableList: FC = function() {
  const [{data, isFetching, count}, refetch] = useList();
  const [{page, pageSize}, {onPageChange}] = usePage(pageContext);
  const [
    {columns, visible, editId, roleVisible, roleId},
    {onAdd, onClose, onRoleClose},
  ] = useHandle(data, refetch);

  return (
    <>
      <Card className='table-wrapper'>
        <section className='table-tool'>
          <Space>
            <Button type='primary' onClick={onAdd} data-testid='add_btn'>新增</Button>
          </Space>
        </section>

        <Table
          data-testid='role_table'
          columns={columns}
          dataSource={data}
          rowKey='id'
          pagination={{
            current: page,
            pageSize,
            onChange: onPageChange,
            pageSizeOptions: PAGE_SIZE_LIST,
            total: count,
            showSizeChanger: true,
          }}
          loading={isFetching}
        />
      </Card>
      <RoleModal visible={visible} onClose={onClose} onFetch={refetch} id={editId} />
      <TreeModal visible={roleVisible} onClose={onRoleClose} onFetch={refetch} id={roleId} />
    </>
  );
};

export default TableList;
