import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, Descriptions, Button, Space, Modal, Form, InputNumber, Input, message, Select } from 'antd';
import { WalletOutlined, ArrowUpOutlined, ArrowDownOutlined, DollarOutlined, ExportOutlined } from '@ant-design/icons';
import { getPlatformAccounts, createPlatformWithdrawal, getBankCards } from '@/api/finance';
import { formatMoney, formatDateTime } from '@rent/shared-utils';

interface PlatformAccount {
  id: number;
  account_name: string;
  balance: number;
  frozen_balance: number;
  total_income: number;
  total_expense: number;
  total_service_fee: number;
  status: string;
  created_at: string;
  updated_at: string;
}

interface BankCard {
  id: number;
  cardName: string;
  bankName: string;
  bankAccount: string;
  accountName: string;
  isDefault: boolean;
  status: string;
}

const PlatformWallet: React.FC = () => {
  const [account, setAccount] = useState<PlatformAccount | null>(null);
  const [loading, setLoading] = useState(false);
  const [withdrawModalVisible, setWithdrawModalVisible] = useState(false);
  const [bankCards, setBankCards] = useState<BankCard[]>([]);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchAccount();
    fetchBankCards();
  }, []);

  const fetchAccount = async () => {
    setLoading(true);
    try {
      const res = await getPlatformAccounts({});
      if (res.data && res.data.length > 0) {
        setAccount(res.data[0]);
      }
    } catch (error) {
      console.error('获取平台账户失败', error);
      message.error('获取平台账户失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchBankCards = async () => {
    try {
      const res = await getBankCards({});
      const cards = res.data.items || res.data || [];
      setBankCards(cards.filter((card: BankCard) => card.status === 'active'));
    } catch (error) {
      console.error('获取银行卡列表失败', error);
    }
  };

  const handleWithdraw = () => {
    if (bankCards.length === 0) {
      message.warning('请先添加银行卡');
      return;
    }
    const defaultCard = bankCards.find(card => card.isDefault);
    if (defaultCard) {
      form.setFieldsValue({
        bankCardId: defaultCard.id,
        bankAccount: defaultCard.bankAccount,
        bankName: defaultCard.bankName,
      });
    }
    setWithdrawModalVisible(true);
  };

  const handleBankCardChange = (bankCardId: number) => {
    const selectedCard = bankCards.find(card => card.id === bankCardId);
    if (selectedCard) {
      form.setFieldsValue({
        bankAccount: selectedCard.bankAccount,
        bankName: selectedCard.bankName,
      });
    }
  };

  const handleWithdrawSubmit = async (values: any) => {
    try {
      await createPlatformWithdrawal({
        amount: values.amount,
        bankAccount: values.bankAccount,
        bankName: values.bankName,
        remark: values.remark,
      });
      message.success('提现申请已提交');
      setWithdrawModalVisible(false);
      form.resetFields();
      fetchAccount();
    } catch (error: any) {
      message.error(error.response?.data?.message || '提现申请失败');
    }
  };

  // 可提现金额 = 钱包余额 - 冻结余额
  const withdrawableAmount = account ? Number(account.balance) - Number(account.frozen_balance) : 0;

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>平台钱包</h2>

      {account && (
        <>
          <Row gutter={24} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="钱包余额"
                  value={account.balance}
                  precision={2}
                  prefix={<WalletOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#1890ff', fontSize: 32 }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  平台可支配金额
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="可提现金额"
                  value={withdrawableAmount}
                  precision={2}
                  prefix={<DollarOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#52c41a', fontSize: 32 }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  钱包余额 - 冻结金额
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="冻结金额"
                  value={account.frozen_balance}
                  precision={2}
                  suffix="元"
                  valueStyle={{ color: '#faad14', fontSize: 32 }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  提现申请中
                </div>
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="服务费收入"
                  value={account.total_service_fee}
                  precision={2}
                  suffix="元"
                  valueStyle={{ color: '#722ed1', fontSize: 32 }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  累计服务费
                </div>
              </Card>
            </Col>
          </Row>

          <Row gutter={24} style={{ marginBottom: 24 }}>
            <Col span={8}>
              <Card>
                <Statistic
                  title="账户总收入"
                  value={account.total_income}
                  precision={2}
                  prefix={<ArrowUpOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#52c41a', fontSize: 24 }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  所有订单支付总额
                </div>
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <Statistic
                  title="账户总支出"
                  value={account.total_expense}
                  precision={2}
                  prefix={<ArrowDownOutlined />}
                  suffix="元"
                  valueStyle={{ color: '#ff4d4f', fontSize: 24 }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  商家结算 + 邀请返现
                </div>
              </Card>
            </Col>
            <Col span={8}>
              <Card>
                <Statistic
                  title="其他收入"
                  value={0}
                  precision={2}
                  suffix="元"
                  valueStyle={{ color: '#13c2c2', fontSize: 24 }}
                />
                <div style={{ fontSize: 12, color: '#999', marginTop: 8 }}>
                  广告费、会员费等
                </div>
              </Card>
            </Col>
          </Row>

          <Card title="钱包详情" loading={loading}>
            <Descriptions column={2} bordered>
              <Descriptions.Item label="账户名称">{account.account_name}</Descriptions.Item>
              <Descriptions.Item label="账户ID">{account.id}</Descriptions.Item>
              <Descriptions.Item label="钱包余额">
                <span style={{ fontSize: 16, fontWeight: 'bold', color: '#1890ff' }}>
                  {formatMoney(account.balance)}
                </span>
              </Descriptions.Item>
              <Descriptions.Item label="可提现金额">
                <span style={{ fontSize: 16, fontWeight: 'bold', color: '#52c41a' }}>
                  {formatMoney(withdrawableAmount)}
                </span>
              </Descriptions.Item>
              <Descriptions.Item label="冻结金额">
                <span style={{ fontSize: 16, color: '#faad14' }}>
                  {formatMoney(account.frozen_balance)}
                </span>
              </Descriptions.Item>
              <Descriptions.Item label="账户状态">
                <span style={{ color: account.status === 'active' ? '#52c41a' : '#ff4d4f' }}>
                  {account.status === 'active' ? '正常' : '冻结'}
                </span>
              </Descriptions.Item>
              <Descriptions.Item label="服务费收入">
                <span style={{ color: '#722ed1', fontSize: 16, fontWeight: 'bold' }}>{formatMoney(account.total_service_fee)}</span>
              </Descriptions.Item>
              <Descriptions.Item label="其他收入">
                <span style={{ color: '#13c2c2' }}>{formatMoney(0)}</span>
              </Descriptions.Item>
              <Descriptions.Item label="账户总收入">
                <span style={{ color: '#52c41a' }}>{formatMoney(account.total_income)}</span>
              </Descriptions.Item>
              <Descriptions.Item label="账户总支出">
                <span style={{ color: '#ff4d4f' }}>{formatMoney(account.total_expense)}</span>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">{formatDateTime(account.created_at)}</Descriptions.Item>
              <Descriptions.Item label="更新时间">{formatDateTime(account.updated_at)}</Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: 24, textAlign: 'right' }}>
              <Space>
                <Button type="primary" icon={<ExportOutlined />} onClick={handleWithdraw}>
                  申请提现
                </Button>
                <Button onClick={fetchAccount}>刷新数据</Button>
              </Space>
            </div>
          </Card>
        </>
      )}

      <Modal
        title="平台钱包提现"
        open={withdrawModalVisible}
        onCancel={() => {
          setWithdrawModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form form={form} layout="vertical" onFinish={handleWithdrawSubmit}>
          <Form.Item label="可提现金额">
            <div style={{ fontSize: 24, fontWeight: 'bold', color: '#52c41a' }}>
              {formatMoney(withdrawableAmount)}
            </div>
            <div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>
              钱包余额 - 冻结金额 = 可提现金额
            </div>
            <div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>
              包含：服务费收入、其他收入，扣除：邀请返现等支出
            </div>
          </Form.Item>
          <Form.Item
            name="bankCardId"
            label="选择银行卡"
            rules={[{ required: true, message: '请选择银行卡' }]}
          >
            <Select
              placeholder="请选择银行卡"
              onChange={handleBankCardChange}
              options={bankCards.map(card => ({
                label: `${card.cardName} - ${card.bankName} (${card.bankAccount.replace(/(\d{4})\d+(\d{4})/, '$1****$2')})`,
                value: card.id,
              }))}
            />
          </Form.Item>
          <Form.Item
            name="amount"
            label="提现金额"
            rules={[
              { required: true, message: '请输入提现金额' },
              {
                validator: (_, value) => {
                  if (value && value > withdrawableAmount) {
                    return Promise.reject(`提现金额不能大于可提现金额（${withdrawableAmount.toFixed(2)}元）`);
                  }
                  if (value && value <= 0) {
                    return Promise.reject('提现金额必须大于0');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入提现金额"
              min={0}
              max={withdrawableAmount}
              precision={2}
              addonAfter="元"
            />
          </Form.Item>
          <Form.Item
            name="bankAccount"
            label="收款账户"
            rules={[{ required: true, message: '请输入收款账户' }]}
          >
            <Input placeholder="请输入银行账号" disabled />
          </Form.Item>
          <Form.Item
            name="bankName"
            label="开户银行"
            rules={[{ required: true, message: '请输入开户银行' }]}
          >
            <Input placeholder="请输入开户银行" disabled />
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={3} placeholder="请输入备注信息（选填）" />
          </Form.Item>
          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => setWithdrawModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit">
                提交申请
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PlatformWallet;
