import React, { useEffect, useState } from 'react';
import { Card, Button, Table, message, Modal, Form, InputNumber, Input, Space, Alert } from 'antd';
import { useNavigate } from 'react-router-dom';
import { ExportOutlined } from '@ant-design/icons';
import { getMerchantAccount, getMerchantTransactions, applyWithdrawal } from '@/api/finance';
import { getMerchantInfo } from '@/api/auth';
import type { ColumnsType } from 'antd/es/table';
import type { Account, Transaction, TransactionType } from '@rent/shared-types';
import { TRANSACTION_TYPE_MAP } from '@rent/shared-types';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { useTableData } from '@/hooks/useTableData';
import { AccountCard } from '@/components/AccountCard';
import { TransactionAmount } from '@/components/TransactionAmount';

const Wallet: React.FC = () => {
  const navigate = useNavigate();
  const [account, setAccount] = useState<Account | null>(null);
  const [accountLoading, setAccountLoading] = useState(false);
  const [withdrawModalVisible, setWithdrawModalVisible] = useState(false);
  const [merchantInfo, setMerchantInfo] = useState<any>(null);
  const [form] = Form.useForm();

  const {
    data: transactions,
    loading,
    total,
    page,
    pageSize,
    setPage,
    setPageSize,
  } = useTableData<Transaction>({
    fetchFn: async (params) => {
      const res = await getMerchantTransactions(params);
      return {
        list: res.data.items,
        total: res.data.total,
        page: params.page || 1,
        pageSize: params.pageSize || 10,
        totalPages: Math.ceil(res.data.total / (params.pageSize || 10)),
      };
    },
  });

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

  const fetchAccount = async () => {
    setAccountLoading(true);
    try {
      const res = await getMerchantAccount();
      setAccount(res.data);
    } catch (error) {
      message.error('获取账户信息失败');
    } finally {
      setAccountLoading(false);
    }
  };

  const handleWithdraw = async () => {
    if (!account || account.availableAmount <= 0) {
      message.warning('可用余额不足，无法提现');
      return;
    }

    // 获取商家信息，读取银行卡信息
    try {
      const res = await getMerchantInfo();
      setMerchantInfo(res.data);

      // 自动填充银行卡信息
      form.setFieldsValue({
        bankAccount: res.data.bankAccount || '',
        bankName: res.data.bankName || '',
      });

      setWithdrawModalVisible(true);
    } catch (error) {
      message.error('获取银行卡信息失败');
    }
  };

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

  const columns: ColumnsType<Transaction> = [
    {
      title: '交易时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (date: string) => formatDateTime(date),
    },
    {
      title: '交易类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: string) => TRANSACTION_TYPE_MAP[type as TransactionType]?.label || type,
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number, record: Transaction) => (
        <TransactionAmount type={record.type} amount={amount} />
      ),
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance: number) => formatMoney(balance),
    },
    {
      title: '说明',
      dataIndex: 'description',
      key: 'description',
    },
  ];

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

      {account && (
        <div style={{ marginBottom: 24 }}>
          <AccountCard account={account} loading={accountLoading} />
          <div style={{ marginTop: 16, textAlign: 'right' }}>
            <Space>
              <Button type="primary" icon={<ExportOutlined />} onClick={handleWithdraw}>
                申请提现
              </Button>
              <Button onClick={fetchAccount}>刷新数据</Button>
            </Space>
          </div>
        </div>
      )}

      <Card
        title="交易记录"
        extra={
          <Button type="primary" onClick={() => navigate('/finance/transactions')}>
            查看全部
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={transactions}
          rowKey="id"
          loading={loading}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: setPage,
            onShowSizeChange: (_, size) => setPageSize(size),
          }}
        />
      </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(account?.availableAmount || 0)}
            </div>
            <div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>
              最低提现金额：100元
            </div>
          </Form.Item>
          <Form.Item
            name="amount"
            label="提现金额"
            rules={[
              { required: true, message: '请输入提现金额' },
              {
                validator: (_, value) => {
                  if (value && value < 100) {
                    return Promise.reject('提现金额不能小于100元');
                  }
                  if (value && value > (account?.availableAmount || 0)) {
                    return Promise.reject('提现金额不能大于可用余额');
                  }
                  if (value && value <= 0) {
                    return Promise.reject('提现金额必须大于0');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入提现金额"
              min={100}
              max={account?.availableAmount || 0}
              precision={2}
              addonAfter="元"
            />
          </Form.Item>

          {merchantInfo && merchantInfo.bankAccount ? (
            <>
              <Alert
                message="将使用以下银行卡信息进行提现"
                type="info"
                showIcon
                style={{ marginBottom: 16 }}
              />
              <Form.Item name="bankAccount" label="收款账户">
                <Input disabled />
              </Form.Item>
              <Form.Item name="bankName" label="开户银行">
                <Input disabled />
              </Form.Item>
              <div style={{ fontSize: 12, color: '#999', marginBottom: 16 }}>
                如需修改银行卡信息，请前往"店铺设置"页面
              </div>
            </>
          ) : (
            <>
              <Alert
                message="未设置银行卡信息"
                description='请先在"店铺设置"页面完善银行卡信息，或手动输入银行卡信息'
                type="warning"
                showIcon
                style={{ marginBottom: 16 }}
              />
              <Form.Item
                name="bankAccount"
                label="收款账户"
                rules={[
                  { required: true, message: '请输入银行账号' },
                  { pattern: /^\d{16,19}$/, message: '请输入正确的银行账号（16-19位数字）' },
                ]}
              >
                <Input placeholder="请输入银行账号" maxLength={19} />
              </Form.Item>
              <Form.Item
                name="bankName"
                label="开户银行"
                rules={[{ required: true, message: '请输入开户银行' }]}
              >
                <Input 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 Wallet;
