import React, { useState, useEffect } from 'react';
import { Modal, Button, Form, Input, InputNumber, message, List } from 'antd';
import { useUserInfo } from '@/store/userStore';
import { ICustomer } from '@/models/types';
import axios from 'axios';

interface RechargeProps {
    visible: boolean;
    onCancel: () => void;
    customer: ICustomer | null;
    onRechargeSuccess: () => void; // 充值成功后的回调
}

const Recharge: React.FC<RechargeProps> = ({ visible, onCancel, customer, onRechargeSuccess }) => {
    const [loading, setLoading] = useState(false);
    const [balance, setBalance] = useState<number | null>(null);
    const [transactions, setTransactions] = useState<any[]>([]); // 存储交易记录
    const [form] = Form.useForm();
    const { 团队 } = useUserInfo();

    useEffect(() => {
        const fetchBalanceAndTransactions = async () => {
            if (customer?._id) {
                try {
                    // 重置状态
                    setBalance(null);
                    setTransactions([]);
                    form.resetFields();

                    // 获取客户余额
                    const balanceResponse = await axios.get(`/api/backstage/balance/${customer._id}`);
                    if (balanceResponse.status === 200) {
                        setBalance(balanceResponse.data.balance ?? 0); // 默认值为 0
                    } else {
                        setBalance(0); // 无法获取余额时设为 0
                    }

                    // 获取客户交易记录
                    const transactionsResponse = await axios.get(`/api/backstage/transactions/${customer._id}`);
                    if (transactionsResponse.status === 200) {
                        setTransactions(transactionsResponse.data.transactions);
                    } else {
                        message.error('无法获取交易记录');
                    }
                } catch (error) {
                    console.error('获取数据时出错:', error);
                    setBalance(0); // 错误情况下设为 0
                    message.error('无余额交易记录');
                }
            }
        };

        if (visible) {
            fetchBalanceAndTransactions();
        }
    }, [customer, visible]);

    const handleRecharge = async () => {
        if (!customer?._id) {
            message.error('请先选择客户');
            return;
        }
        try {
            setLoading(true);
            const values = await form.validateFields();
            const { 金额, 描述 } = values;

            const response = await axios.post('/api/backstage/transactions', {
                团队: 团队?._id,
                客户: customer?._id,
                类型: '充值',
                金额,
                描述,
            });

            if (response.status === 200) {
                message.success('充值成功');
                onRechargeSuccess();
                onCancel();
            } else {
                message.error('充值失败，请重试');
            }
        } catch (error) {
            message.error('充值失败，请检查输入并重试');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal
            open={visible}
            //title="充值"
            title={<div className="text-2xl">客户充值</div>}
            onCancel={onCancel}
            footer={[
                <Button key="back" onClick={onCancel}>
                    取消
                </Button>,
                <Button key="submit" type="primary" loading={loading} onClick={handleRecharge}>
                    确认充值
                </Button>,
            ]}
        >
            {balance !== null && balance !== undefined ? (
                <div style={{ marginBottom: '16px' }}>
                    <h2>当前余额: ¥ {balance.toFixed(2)}</h2>
                </div>
            ) : (
                <div style={{ marginBottom: '16px' }}>
                    <strong>当前余额: ¥ 0</strong>
                </div>
            )}

            <Form form={form} layout="vertical">
                <Form.Item
                    name="金额"
                    label="充值金额"
                    rules={[{ required: true, message: '请输入充值金额' }]}
                >
                    <InputNumber min={0.01} step={0.01} precision={2} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item
                    name="描述"
                    label="描述"
                >
                    <Input placeholder="可选，填写描述信息" />
                </Form.Item>
            </Form>

            <div style={{ marginTop: '24px' }}>
                <h3>余额交易记录</h3>
                <div style={{ maxHeight: '320px', overflowY: 'auto' }}>
                    <List
                        itemLayout="horizontal"
                        dataSource={transactions}
                        renderItem={item => (
                            <List.Item>
                                <List.Item.Meta
                                    title={`类型: ${item.类型}`}
                                    description={`金额: ¥${item.金额.toFixed(2)} - 日期: ${new Date(item.日期).toLocaleDateString()} - 描述: ${item.描述}`}
                                />
                            </List.Item>
                        )}
                    />
                </div>
            </div>
        </Modal>
    );
};

export default Recharge;
