import React, { useRef, useState } from 'react';
import Table, { ProColumns, ActionType } from '@/components/Table';
import { message } from 'antd';
import { fetchTableData } from '@/utils/table';
import AddNftModal from './components/AddNftModel';
import { initWeb3, NFTMint } from '@/utils/web3';
import { getContractInfo } from '@/services/contract';
import { ContractType } from '@/constants/enum/contract';
import { checkTokenId, getNFTContractList, getNFTList, mintNFT } from '@/services/nft';

const Address: React.FC = () => {
  const tableRef = useRef<ActionType>();
  const [visible, setVisible] = useState(false);

  const columns: ProColumns<any>[] = [
    {
      title: 'TokenId',
      dataIndex: 'token_id',
      width: '10%',
      hideInSearch: true,
    },
    {
      title: '所有者地址',
      dataIndex: 'address',
      hideInSearch: true,
    },
    {
      title: 'NFT名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '图片',
      dataIndex: 'image',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '缩略图',
      dataIndex: 'avatar',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInSearch: true,
    },
  ];

  return (
    <div>
      <Table
        columns={columns}
        rowKey="id"
        search={false}
        actionRef={tableRef}
        toolBarActions={[
          {
            type: 'add',
            text: '添加NFT',
            onConfirm: () => {
              setVisible(true);
            },
          },
        ]}
        request={async (params) => {
          const res = await fetchTableData(getNFTList, params);
          return res;
        }}
      />
      <AddNftModal
        visible={visible}
        onCancel={function () {
          setVisible(false);
        }}
        onOk={async function (val: any): Promise<void> {
          await checkTokenId({ token_id: val.token_id });
          await initWeb3();
          const contractInfo = await getContractInfo({ erc: ContractType.NFT721 });
          const res = await getNFTContractList();
          await NFTMint({
            abi: contractInfo.abi,
            address: res.items[0].address,
            toAddress: val.toAddress,
            name: val.name,
            token_id: val.token_id,
          });
          await mintNFT(val);
          tableRef.current?.reload();
          setVisible(false);
        }}
      />
    </div>
  );
};

export default Address;
