import React from 'react';
import { Card, Table, Button, Space, Modal, message, Descriptions } from 'antd';
import { getMerchantWithdrawals, cancelWithdrawal } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import type { Withdrawal } from '@rent/shared-types';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';
import { useModal } from '@/hooks/useModal';
import { WithdrawalStatusTag } from '@/components/WithdrawalStatusTag';

const Withdrawals: React.FC = () => {
  const {
    data: withdrawals,
    loading,
    total,
    page,
    pageSize,
    setPage,
    setPageSize,
    refresh,
  } = useTableData<Withdrawal>({
    fetchFn: async (params) => {
      const res = await getMerchantWithdrawals(params);
      return {
        list: res.data.items,
        total: res.data.total,
        page: params.page || 1,
        pageSize: params.pageSize || 20,
        totalPages: Math.ceil(res.data.total / (params.pageSize || 20)),
      };
    },
    initialParams: { pageSize: 20 },
  });

  const detailModal = useModal<Withdrawal>();

  const handleCancel = async (id: number) => {
    Modal.confirm({
      title: '确认取消',
      content: '确定要取消这笔提现申请吗？',
      onOk: async () => {
        try {
          await cancelWithdrawal(id);
          message.success('取消成功');
          refresh();
        } catch (error: any) {
          message.error(error.response?.data?.message || '取消失败');
        }
      },
    });
  };

  const handleViewDetail = async (withdrawal: Withdrawal) => {
    detailModal.open(withdrawal);
  };

  const columns: ColumnsType<Withdrawal> = [
    {
      title: '提现ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '申请时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '提现金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number) => formatMoney(amount),
    },
    {
      title: '手续费',
      dataIndex: 'fee',
      key: 'fee',
      width: 100,
      render: (fee: number) => formatMoney(fee),
    },
    {
      title: '到账金额',
      dataIndex: 'actualAmount',
      key: 'actualAmount',
      width: 120,
      render: (actualAmount: number) => (
        <span style={{ fontWeight: 'bold', color: '#52c41a' }}>{formatMoney(actualAmount)}</span>
      ),
    },
    {
      title: '收款账户',
      key: 'account',
      width: 200,
      render: (_, record: Withdrawal) => (
        <div>
          <div>{record.bankName}</div>
          <div style={{ fontSize: 12, color: '#999' }}>{record.bankAccount}</div>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => <WithdrawalStatusTag status={status} />,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record: Withdrawal) => (
        <Space>
          <Button type="link" size="small" onClick={() => handleViewDetail(record)}>
            详情
          </Button>
          {record.status === 'pending' && (
            <Button type="link" size="small" danger onClick={() => handleCancel(record.id)}>
              取消
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>提现管理</h2>

      <Card
        extra={
          <div style={{ color: '#999', fontSize: 14 }}>
            如需申请提现，请前往"我的钱包"页面
          </div>
        }
      >
        <Table
          columns={columns}
          dataSource={withdrawals}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: setPage,
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </Card>

      <Modal
        title="提现详情"
        open={detailModal.visible}
        onCancel={detailModal.close}
        footer={null}
        width={600}
      >
        {detailModal.data && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="提现ID">{detailModal.data.id}</Descriptions.Item>
            <Descriptions.Item label="申请时间">{formatDateTime(detailModal.data.createdAt)}</Descriptions.Item>
            <Descriptions.Item label="提现金额">{formatMoney(detailModal.data.amount)}</Descriptions.Item>
            <Descriptions.Item label="手续费">{formatMoney(detailModal.data.fee)}</Descriptions.Item>
            <Descriptions.Item label="到账金额">
              <span style={{ fontWeight: 'bold', color: '#52c41a' }}>
                {formatMoney(detailModal.data.actualAmount)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="开户银行">{detailModal.data.bankName}</Descriptions.Item>
            <Descriptions.Item label="银行账号">{detailModal.data.bankAccount}</Descriptions.Item>
            <Descriptions.Item label="账户名称">{detailModal.data.accountName}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <WithdrawalStatusTag status={detailModal.data.status} />
            </Descriptions.Item>
            {detailModal.data.completedAt && (
              <Descriptions.Item label="完成时间">{formatDateTime(detailModal.data.completedAt)}</Descriptions.Item>
            )}
            {detailModal.data.rejectReason && (
              <Descriptions.Item label="拒绝原因">
                <span style={{ color: '#ff4d4f' }}>{detailModal.data.rejectReason}</span>
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default Withdrawals;
