import React, { useEffect, useState } from 'react';
import { Card, Table, Tag, Button, Space, Modal, Form, Input, message, Descriptions, DatePicker, Tabs } from 'antd';
import { CheckOutlined, CloseOutlined, EyeOutlined } from '@ant-design/icons';
import {
  getUserWithdrawals,
  getMerchantWithdrawals,
  getPlatformWithdrawals,
  approveUserWithdrawal,
  rejectUserWithdrawal,
  confirmUserWithdrawal,
  approveMerchantWithdrawal,
  rejectMerchantWithdrawal,
  confirmMerchantWithdrawal
} from '@/api/finance';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

interface Withdrawal {
  id: number;
  type: string;
  userId?: number;
  merchantId?: number;
  userName?: string;
  merchantName?: string;
  amount: number;
  fee: number;
  actualAmount: number;
  status: string;
  bankAccount: string;
  bankName: string;
  accountName: string;
  rejectReason?: string;
  transactionNo?: string;
  createdAt: string;
  processedAt?: string;
  paidAt?: string;
}

const Withdrawals: React.FC = () => {
  const [form] = Form.useForm();
  const [rejectForm] = Form.useForm();
  const [confirmForm] = Form.useForm();
  const [withdrawalType, setWithdrawalType] = useState<'user' | 'merchant' | 'platform'>('user');
  const [withdrawals, setWithdrawals] = useState<Withdrawal[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 20, total: 0 });
  const [detailVisible, setDetailVisible] = useState(false);
  const [rejectVisible, setRejectVisible] = useState(false);
  const [confirmVisible, setConfirmVisible] = useState(false);
  const [currentDetail, setCurrentDetail] = useState<Withdrawal | null>(null);
  const [currentId, setCurrentId] = useState<number | null>(null);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    fetchWithdrawals();
  }, [withdrawalType]);

  const fetchWithdrawals = async (params: any = {}) => {
    setLoading(true);
    try {
      const queryParams = {
        ...params,
        page: params.page || pagination.current,
        pageSize: params.pageSize || pagination.pageSize,
      };

      let res;
      if (withdrawalType === 'user') {
        res = await getUserWithdrawals(queryParams);
      } else if (withdrawalType === 'merchant') {
        res = await getMerchantWithdrawals(queryParams);
      } else {
        res = await getPlatformWithdrawals(queryParams);
      }

      setWithdrawals(res.data.items || []);
      setPagination({ ...pagination, total: res.data.total || 0, ...params });
    } catch (error) {
      message.error('获取提现记录失败');
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = async (id: number) => {
    try {
      // TODO: 实现提现详情接口
      message.info('提现详情功能待实现');
      // const res = await getWithdrawalDetail(id);
      // setCurrentDetail(res.data);
      // setDetailVisible(true);
    } catch (error) {
      message.error('获取提现详情失败');
    }
  };

  const handleApprove = async (id: number) => {
    Modal.confirm({
      title: '确认通过',
      content: '确定要通过这笔提现申请吗？',
      onOk: async () => {
        try {
          if (withdrawalType === 'user') {
            await approveUserWithdrawal(id);
          } else if (withdrawalType === 'merchant') {
            await approveMerchantWithdrawal(id);
          }
          message.success('审核通过');
          fetchWithdrawals();
        } catch (error: any) {
          message.error(error.response?.data?.message || '操作失败');
        }
      },
    });
  };

  const handleReject = async (values: any) => {
    if (!currentId) return;
    setSubmitting(true);
    try {
      if (withdrawalType === 'user') {
        await rejectUserWithdrawal(currentId, values.reason);
      } else if (withdrawalType === 'merchant') {
        await rejectMerchantWithdrawal(currentId, values.reason);
      }
      message.success('已拒绝');
      setRejectVisible(false);
      rejectForm.resetFields();
      fetchWithdrawals();
    } catch (error: any) {
      message.error(error.response?.data?.message || '操作失败');
    } finally {
      setSubmitting(false);
    }
  };

  const handleConfirm = async (values: any) => {
    if (!currentId) return;
    setSubmitting(true);
    try {
      if (withdrawalType === 'user') {
        await confirmUserWithdrawal(currentId, values.transactionNo);
      } else if (withdrawalType === 'merchant') {
        await confirmMerchantWithdrawal(currentId, values.transactionNo);
      }
      message.success('打款确认成功');
      setConfirmVisible(false);
      confirmForm.resetFields();
      fetchWithdrawals();
    } catch (error: any) {
      message.error(error.response?.data?.message || '操作失败');
    } finally {
      setSubmitting(false);
    }
  };

  const columns: ColumnsType<Withdrawal> = [
    {
      title: '提现ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '申请人',
      key: 'applicant',
      width: 150,
      render: (_, record: Withdrawal) => (
        <div>
          <div>{record.userName || record.merchantName}</div>
          <div style={{ fontSize: 12, color: '#999' }}>
            ID: {record.userId || record.merchantId}
          </div>
        </div>
      ),
    },
    {
      title: '提现金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '手续费',
      dataIndex: 'fee',
      key: 'fee',
      width: 100,
      render: (fee: number) => `¥${fee.toFixed(2)}`,
    },
    {
      title: '到账金额',
      dataIndex: 'actualAmount',
      key: 'actualAmount',
      width: 120,
      render: (actualAmount: number) => (
        <span style={{ fontWeight: 'bold', color: '#52c41a' }}>¥{actualAmount.toFixed(2)}</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: string) => {
        const statusMap: Record<string, { text: string; color: string }> = {
          pending: { text: '待审核', color: 'orange' },
          approved: { text: '已通过', color: 'blue' },
          rejected: { text: '已拒绝', color: 'red' },
          completed: { text: '已打款', color: 'green' },
          cancelled: { text: '已取消', color: 'default' },
        };
        const config = statusMap[status] || { text: status, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '申请时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record: Withdrawal) => (
        <Space>
          <Button type="link" size="small" icon={<EyeOutlined />} onClick={() => handleViewDetail(record.id)}>
            详情
          </Button>
          {record.status === 'pending' && (
            <>
              <Button
                type="link"
                size="small"
                icon={<CheckOutlined />}
                onClick={() => handleApprove(record.id)}
              >
                通过
              </Button>
              <Button
                type="link"
                size="small"
                danger
                icon={<CloseOutlined />}
                onClick={() => {
                  setCurrentId(record.id);
                  setRejectVisible(true);
                }}
              >
                拒绝
              </Button>
            </>
          )}
          {record.status === 'approved' && (
            <Button
              type="link"
              size="small"
              onClick={() => {
                setCurrentId(record.id);
                setConfirmVisible(true);
              }}
            >
              确认打款
            </Button>
          )}
        </Space>
      ),
    },
  ];

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

      <Card>
        <Tabs
          activeKey={withdrawalType}
          onChange={(key) => {
            setWithdrawalType(key as 'user' | 'merchant' | 'platform');
            setPagination({ current: 1, pageSize: 20, total: 0 });
          }}
          items={[
            { key: 'user', label: '用户提现' },
            { key: 'merchant', label: '商家提现' },
            { key: 'platform', label: '平台提现' },
          ]}
          style={{ marginBottom: 16 }}
        />
        <Table
          columns={columns}
          dataSource={withdrawals}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1300 }}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => fetchWithdrawals({ page, pageSize }),
          }}
        />
      </Card>

      <Modal
        title="提现详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={600}
      >
        {currentDetail && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="提现ID">{currentDetail.id}</Descriptions.Item>
            <Descriptions.Item label="申请人">
              {currentDetail.userName || currentDetail.merchantName} (ID: {currentDetail.userId || currentDetail.merchantId})
            </Descriptions.Item>
            <Descriptions.Item label="申请时间">{currentDetail.createdAt}</Descriptions.Item>
            <Descriptions.Item label="提现金额">¥{currentDetail.amount.toFixed(2)}</Descriptions.Item>
            <Descriptions.Item label="手续费">¥{currentDetail.fee.toFixed(2)}</Descriptions.Item>
            <Descriptions.Item label="到账金额">
              <span style={{ fontWeight: 'bold', color: '#52c41a' }}>
                ¥{currentDetail.actualAmount.toFixed(2)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="开户银行">{currentDetail.bankName}</Descriptions.Item>
            <Descriptions.Item label="银行账号">{currentDetail.bankAccount}</Descriptions.Item>
            <Descriptions.Item label="账户名称">{currentDetail.accountName}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={currentDetail.status === 'completed' ? 'green' : 'orange'}>
                {currentDetail.status === 'pending' && '待审核'}
                {currentDetail.status === 'approved' && '已通过'}
                {currentDetail.status === 'rejected' && '已拒绝'}
                {currentDetail.status === 'completed' && '已打款'}
                {currentDetail.status === 'cancelled' && '已取消'}
              </Tag>
            </Descriptions.Item>
            {currentDetail.processedAt && (
              <Descriptions.Item label="处理时间">{currentDetail.processedAt}</Descriptions.Item>
            )}
            {currentDetail.paidAt && (
              <Descriptions.Item label="打款时间">{currentDetail.paidAt}</Descriptions.Item>
            )}
            {currentDetail.transactionNo && (
              <Descriptions.Item label="交易单号">{currentDetail.transactionNo}</Descriptions.Item>
            )}
            {currentDetail.rejectReason && (
              <Descriptions.Item label="拒绝原因">
                <span style={{ color: '#ff4d4f' }}>{currentDetail.rejectReason}</span>
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>

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

      <Modal
        title="确认打款"
        open={confirmVisible}
        onCancel={() => {
          setConfirmVisible(false);
          confirmForm.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form form={confirmForm} layout="vertical" onFinish={handleConfirm}>
          <Form.Item
            name="transactionNo"
            label="交易单号"
            rules={[{ required: true, message: '请输入交易单号' }]}
          >
            <Input placeholder="请输入银行交易单号" />
          </Form.Item>
          <Form.Item
            name="paidAt"
            label="打款时间"
            rules={[{ required: true, message: '请选择打款时间' }]}
            initialValue={dayjs()}
          >
            <DatePicker showTime style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setConfirmVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit" loading={submitting}>
                确认
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Withdrawals;
