import React, { useState, useRef } from 'react';
import Table, { ProColumns, ActionType } from '@/components/Table';
import {
  getAddressList,
  deleteAddress,
  createAddress,
  modifyAddress,
} from '@/services/recharge/wallet';

import { fetchTableData } from '@/utils/table';
import DeleteButton from '@/components/Table/DeleteButton';
import AddWalletModal from '../components/AddWalletModal';
import EditWalletModal from '../components/EditWalletModal';

const CollectionAddressList = () => {
  const tableRef = useRef<ActionType>();

  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [modalData, setModalData] = useState({});

  const handleEdit = (row: any) => {
    row.new_address = '';
    setModalData(row);
    setIsEditModalVisible(true);
  };

  const handleDelete = async (address: any) => {
    await deleteAddress({ address: address });
    tableRef.current?.reload();
  };

  const columns: ProColumns<any>[] = [
    {
      title: '收款地址',
      dataIndex: 'address',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '收款游戏币名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      render: (_, row) => [
        <a
          key="edit"
          onClick={() => {
            handleEdit(row);
          }}
        >
          编辑
        </a>,
        <DeleteButton
          key="delete"
          onDelete={() => {
            handleDelete(row.address);
          }}
        />,
      ],
    },
  ];
  return (
    <div>
      <Table
        columns={columns}
        search={false}
        rowKey="id"
        toolBarActions={[
          {
            type: 'add',
            onConfirm: () => {
              setIsModalVisible(true);
            },
          },
        ]}
        actionRef={tableRef}
        request={async (params) => {
          const res = await fetchTableData(getAddressList, params);
          return res;
        }}
      />
      <AddWalletModal
        visible={isModalVisible}
        onCancel={function () {
          setIsModalVisible(false);
        }}
        onOk={async function (val: any): Promise<void> {
          await createAddress(val);
          setIsModalVisible(false);
          tableRef.current?.reload();
        }}
      />
      <EditWalletModal
        visible={isEditModalVisible}
        editModalData={modalData}
        onCancel={function () {
          setIsEditModalVisible(false);
        }}
        onOk={async function (val: any): Promise<void> {
          await modifyAddress(val);
          setIsEditModalVisible(false);
          tableRef.current?.reload();
        }}
      />
    </div>
  );
};

export default CollectionAddressList;
