import React, { useState, ChangeEvent, FormEvent } from 'react';
import { Input, Button, Typography, message } from 'antd';
import { useAuth } from '@/contexts/AuthContext';
import { api as apiService } from '@/services/api';
import { BaseResponse } from '@/types/api'; // 假设 BaseResponse 移到了这里

interface RedeemCodeFormProps {
    onSuccess?: () => void; // 兑换成功后的回调
    onCancel?: () => void;  // 可选的取消/关闭回调
}

const RedeemCodeForm: React.FC<RedeemCodeFormProps> = ({ onSuccess, onCancel }) => {
    const [code, setCode] = useState<string>('');
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const { isAuthenticated, checkAuth } = useAuth(); // checkAuth 用于成功后刷新用户信息

    const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        setCode(e.target.value.trim());
        setError(null);
    };

    const handleSubmit = async (e?: FormEvent<HTMLFormElement>) => {
        if (e) e.preventDefault();

        if (!isAuthenticated) {
            message.error('请先登录后再兑换激活码。');
            return;
        }
        if (!code) {
            setError('请输入激活码。');
            message.error('请输入激活码。');
            return;
        }
        setIsLoading(true);
        setError(null);

        try {
            const response = await apiService.post<BaseResponse<boolean>>('/activation-code/redeem', 
                { code } 
            );

            console.log('Backend response for redeem:', response.data);

            if (response.data && response.data.code === 0 && response.data.data === true) {
                message.success('激活码兑换成功！您的余额已更新。');
                setCode('');
                await checkAuth(); // 刷新用户信息，特别是余额
                if (onSuccess) onSuccess();
            } else {
                const errorMessage = response.data?.message || '兑换失败，请稍后再试。';
                setError(errorMessage);
                message.error(errorMessage);
            }
        } catch (err: any) {
            console.error('Redeem code error:', err);
            const errorMessage = err.response?.data?.message || err.message || '兑换过程中发生错误。';
            setError(errorMessage);
            message.error(errorMessage);
        }
        setIsLoading(false);
    };

    return (
        <form onSubmit={handleSubmit}>
            <Input
                placeholder="请输入您的激活码"
                value={code}
                onChange={handleInputChange}
                size="large"
                style={{ marginBottom: '20px' }}
                disabled={isLoading || !isAuthenticated}
            />
            {error && (
                <Typography.Text type="danger" style={{ display: 'block', marginBottom: '10px' }}>
                    {error}
                </Typography.Text>
            )}
            <Button 
                type="primary" 
                htmlType="submit" 
                loading={isLoading} 
                disabled={!isAuthenticated || !code.trim()} 
                block 
                size="large"
                style={{ marginBottom: onCancel ? '10px' : '0' }} // 如果有取消按钮，给兑换按钮留点空间
            >
                {isLoading ? '兑换中...' : '立即兑换'}
            </Button>
            {onCancel && (
                 <Button 
                    onClick={onCancel} 
                    block 
                    size="large"
                    disabled={isLoading}
                >
                    取消
                </Button>
            )}
            {!isAuthenticated && (
                 <Typography.Text type="warning" style={{ display: 'block', marginTop: '10px', textAlign: 'center' }}>
                    请先登录以兑换激活码。
                </Typography.Text>
            )}
        </form>
    );
};

export default RedeemCodeForm; 