'use client';
import React, { useState, ChangeEvent, FormEvent } from 'react';
import { Input, Button, Card, Typography, message } from 'antd';
import { useAuth } from '@/contexts/AuthContext';
import { api as apiService } from '@/services/api';

// 暂时在此处定义 BaseResponse，因为 @/services/api.ts 未导出它
// 理想情况下，它应该在全局类型定义文件中或与api实例一起导出
export interface BaseResponse<T> {
    code: number;
    data: T;
    message?: string;
}

const { Title } = Typography;

const RedeemActivationCodePage = () => {
    const [code, setCode] = useState<string>('');
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const { isAuthenticated } = useAuth();

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

    const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
        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>>('/api/activation-code/redeem', 
                { code }
            );

            if (response.data && response.data.code === 0 && response.data.data === true) {
                message.success('激活码兑换成功！您的余额已更新。');
                setCode('');
            } else {
                const errorMessage = response.data?.message || '兑换失败，请稍后再试。';
                setError(errorMessage);
                message.error(errorMessage);
            }
        } catch (err: unknown) {
            console.error('Redeem code error:', err);
            let apiErrorMessage: string | undefined;

            if (typeof err === 'object' && err !== null) {
                // Attempt to access properties in a type-safe manner
                const potentialError = err as { 
                    response?: { data?: { message?: string } }, 
                    message?: string 
                };
                apiErrorMessage = potentialError.response?.data?.message || potentialError.message;
            }
            
            const errorMessage = apiErrorMessage || '兑换过程中发生错误，请检查网络或联系管理员。';
            setError(errorMessage);
            message.error(errorMessage);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div style={{ maxWidth: '500px', margin: '50px auto', padding: '20px' }}>
            <Card bordered={false}>
                <Title level={3} style={{ textAlign: 'center', marginBottom: '30px' }}>
                    兑换激活码
                </Title>
                <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}
                        block 
                        size="large"
                    >
                        {isLoading ? '兑换中...' : '立即兑换'}
                    </Button>
                    {!isAuthenticated && (
                         <Typography.Text type="warning" style={{ display: 'block', marginTop: '10px', textAlign: 'center' }}>
                            请先登录以兑换激活码。
                        </Typography.Text>
                    )}
                </form>
            </Card>
        </div>
    );
};

export default RedeemActivationCodePage; 