import React, { useState } from 'react';
import { Card, Table, Form, Input, Button, Space, Select, Tag, Descriptions, Modal, message } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { getPlatformWithdrawals, approvePlatformWithdrawal, rejectPlatformWithdrawal, confirmPlatformWithdrawal } from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';
import { useModal } from '@/hooks/useModal';

interface PlatformWithdrawal {
  id: number;
  withdrawal_no: string;
  account_id: number;
  amount: number;
  bank_account: string;
  bank_name: string;
  account_name: string;
  status: 'pending' | 'approved' | 'rejected' | 'paid' | 'failed';
  remark?: string;
  reject_reason?: string;
  reviewer_id?: number;
  reviewed_at?: string;
  payment_no?: string;
  paid_at?: string;
  created_at: string;
}

const statusConfig = {
  pending: { text: '待审核', color: 'orange' },
  approved: { text: '已审核', color: 'blue' },
  rejected: { text: '已拒绝', color: 'red' },
  paid: { text: '已打款', color: 'green' },
  failed: { text: '打款失败', color: 'red' },
};

const PlatformWithdrawals: React.FC = () => {
  const [form] = Form.useForm();
  const [rejectForm] = Form.useForm();
  const [confirmForm] = Form.useForm();
  const detailModal = useModal<PlatformWithdrawal>();
  const rejectModal = useModal<PlatformWithdrawal>();
  const confirmModal = useModal<PlatformWithdrawal>();

  const {
    data: withdrawals,
    loading,
    total,
    page,
    pageSize,
    setPage,
    setPageSize,
    refresh,
  } = useTableData<PlatformWithdrawal>({
    fetchFn: async (params) => {
      const res = await getPlatformWithdrawals(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 handleSearch = () => {
    const values = form.getFieldsValue();
    refresh({ ...values, page: 1 });
  };

  const handleReset = () => {
    form.resetFields();
    refresh({ page: 1 });
  };

  const handleViewDetail = (record: PlatformWithdrawal) => {
    detailModal.open(record);
  };

  const handleApprove = async (record: PlatformWithdrawal) => {
    Modal.confirm({
      title: '确认审核通过',
      content: `确定要审核通过提现申请 ${record.withdrawal_no} 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await approvePlatformWithdrawal(record.id);
          message.success('审核通过成功');
          refresh();
        } catch (error: any) {
          message.error(error.response?.data?.message || '审核失败');
        }
      },
    });
  };

  const handleReject = (record: PlatformWithdrawal) => {
    rejectModal.open(record);
  };

  const handleRejectSubmit = async (values: any) => {
    if (!rejectModal.data) return;
    try {
      await rejectPlatformWithdrawal(rejectModal.data.id, values.rejectReason);
      message.success('已拒绝提现申请');
      rejectModal.close();
      rejectForm.resetFields();
      refresh();
    } catch (error: any) {
      message.error(error.response?.data?.message || '操作失败');
    }
  };

  const handleConfirm = (record: PlatformWithdrawal) => {
    confirmModal.open(record);
  };

  const handleConfirmSubmit = async (values: any) => {
    if (!confirmModal.data) return;
    try {
      await confirmPlatformWithdrawal(confirmModal.data.id, values.paymentNo);
      message.success('打款确认成功');
      confirmModal.close();
      confirmForm.resetFields();
      refresh();
    } catch (error: any) {
      message.error(error.response?.data?.message || '操作失败');
    }
  };

  const columns: ColumnsType<PlatformWithdrawal> = [
    {
      title: '提现单号',
      dataIndex: 'withdrawal_no',
      key: 'withdrawal_no',
      width: 180,
      fixed: 'left',
    },
    {
      title: '提现金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number) => (
        <span style={{ fontWeight: 'bold', color: '#ff4d4f' }}>{formatMoney(amount)}</span>
      ),
    },
    {
      title: '收款账户',
      dataIndex: 'bank_account',
      key: 'bank_account',
      width: 180,
    },
    {
      title: '开户银行',
      dataIndex: 'bank_name',
      key: 'bank_name',
      width: 150,
    },
    {
      title: '账户名称',
      dataIndex: 'account_name',
      key: 'account_name',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = statusConfig[status as keyof typeof statusConfig] || { text: status, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '申请时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '审核时间',
      dataIndex: 'reviewed_at',
      key: 'reviewed_at',
      width: 180,
      render: (date: string) => (date ? formatDateTime(date) : '-'),
    },
    {
      title: '打款时间',
      dataIndex: 'paid_at',
      key: 'paid_at',
      width: 180,
      render: (date: string) => (date ? formatDateTime(date) : '-'),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record: PlatformWithdrawal) => (
        <Space>
          <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>
            详情
          </Button>
          {record.status === 'pending' && (
            <>
              <Button
                type="link"
                size="small"
                icon={<CheckOutlined />}
                onClick={() => handleApprove(record)}
                style={{ color: '#52c41a' }}
              >
                通过
              </Button>
              <Button
                type="link"
                size="small"
                icon={<CloseOutlined />}
                onClick={() => handleReject(record)}
                danger
              >
                拒绝
              </Button>
            </>
          )}
          {record.status === 'approved' && (
            <Button type="link" size="small" onClick={() => handleConfirm(record)}>
              确认打款
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>平台服务费提现管理</h2>

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Form form={form} layout="inline">
            <Form.Item name="withdrawalNo" label="提现单号">
              <Input placeholder="请输入提现单号" style={{ width: 180 }} />
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select placeholder="请选择" style={{ width: 120 }} allowClear>
                <Select.Option value="pending">待审核</Select.Option>
                <Select.Option value="approved">已审核</Select.Option>
                <Select.Option value="rejected">已拒绝</Select.Option>
                <Select.Option value="paid">已打款</Select.Option>
                <Select.Option value="failed">打款失败</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                  查询
                </Button>
                <Button icon={<ReloadOutlined />} onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>

        <Table
          columns={columns}
          dataSource={withdrawals}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1600 }}
          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={700}
      >
        {detailModal.data && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="提现单号">{detailModal.data.withdrawal_no}</Descriptions.Item>
            <Descriptions.Item label="提现金额">
              <span style={{ fontSize: 18, fontWeight: 'bold', color: '#ff4d4f' }}>
                {formatMoney(detailModal.data.amount)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="收款账户">{detailModal.data.bank_account}</Descriptions.Item>
            <Descriptions.Item label="开户银行">{detailModal.data.bank_name}</Descriptions.Item>
            <Descriptions.Item label="账户名称">{detailModal.data.account_name}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={statusConfig[detailModal.data.status].color}>
                {statusConfig[detailModal.data.status].text}
              </Tag>
            </Descriptions.Item>
            {detailModal.data.remark && (
              <Descriptions.Item label="备注">{detailModal.data.remark}</Descriptions.Item>
            )}
            {detailModal.data.reject_reason && (
              <Descriptions.Item label="拒绝原因">
                <span style={{ color: '#ff4d4f' }}>{detailModal.data.reject_reason}</span>
              </Descriptions.Item>
            )}
            {detailModal.data.payment_no && (
              <Descriptions.Item label="打款流水号">{detailModal.data.payment_no}</Descriptions.Item>
            )}
            <Descriptions.Item label="申请时间">{formatDateTime(detailModal.data.created_at)}</Descriptions.Item>
            {detailModal.data.reviewed_at && (
              <Descriptions.Item label="审核时间">{formatDateTime(detailModal.data.reviewed_at)}</Descriptions.Item>
            )}
            {detailModal.data.paid_at && (
              <Descriptions.Item label="打款时间">{formatDateTime(detailModal.data.paid_at)}</Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>

      <Modal
        title="拒绝提现申请"
        open={rejectModal.visible}
        onCancel={() => {
          rejectModal.close();
          rejectForm.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form form={rejectForm} layout="vertical" onFinish={handleRejectSubmit}>
          <Form.Item
            name="rejectReason"
            label="拒绝原因"
            rules={[{ required: true, message: '请输入拒绝原因' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入拒绝原因" />
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => rejectModal.close()}>取消</Button>
              <Button type="primary" danger htmlType="submit">
                确认拒绝
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="确认打款"
        open={confirmModal.visible}
        onCancel={() => {
          confirmModal.close();
          confirmForm.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form form={confirmForm} layout="vertical" onFinish={handleConfirmSubmit}>
          <Form.Item label="提现金额">
            <div style={{ fontSize: 24, fontWeight: 'bold', color: '#ff4d4f' }}>
              {confirmModal.data && formatMoney(confirmModal.data.amount)}
            </div>
          </Form.Item>
          <Form.Item
            name="paymentNo"
            label="打款流水号"
            rules={[{ required: true, message: '请输入打款流水号' }]}
          >
            <Input placeholder="请输入银行打款流水号" />
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => confirmModal.close()}>取消</Button>
              <Button type="primary" htmlType="submit">
                确认打款
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PlatformWithdrawals;
