import { useState } from 'react';
import { Send, CheckCircle, Loader2, Mail, Sparkles } from 'lucide-react';

interface EmailSubscribeProps {
    onSuccess?: () => void;
}

const EmailSubscribe = ({ onSuccess }: EmailSubscribeProps) => {
    const [email, setEmail] = useState('');
    const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
    const [message, setMessage] = useState('');

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!email) {
            setStatus('error');
            setMessage('请输入您的邮箱地址');
            return;
        }

        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            setStatus('error');
            setMessage('请输入有效的邮箱地址');
            return;
        }

        setStatus('loading');
        setMessage('');

        try {
            const response = await fetch('/api/send-welcome-email', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ email }),
            });

            const data = await response.json();

            if (data.success) {
                setStatus('success');
                setMessage(data.message || '欢迎邮件已发送！请查收您的邮箱。');
                setEmail('');
                onSuccess?.();
            } else {
                setStatus('error');
                setMessage(data.message || '发送失败，请稍后重试');
            }
        } catch (error) {
            console.error('Error sending email:', error);
            setStatus('error');
            setMessage('网络错误，请检查连接后重试');
        }
    };

    if (status === 'success') {
        return (
            <div className="w-full max-w-md mx-auto">
                <div className="bg-[#112240] border border-[#64FFDA]/30 rounded-2xl p-8 text-center transform animate-pulse">
                    <div className="w-16 h-16 bg-[#64FFDA]/20 rounded-full flex items-center justify-center mx-auto mb-4">
                        <CheckCircle className="w-8 h-8 text-[#64FFDA]" />
                    </div>
                    <h3 className="text-xl font-bold text-white mb-2">邮件已发送！ 🎉</h3>
                    <p className="text-slate-400 text-sm">{message}</p>
                    <button
                        onClick={() => {
                            setStatus('idle');
                            setMessage('');
                        }}
                        className="mt-6 text-[#64FFDA] text-sm hover:underline"
                    >
                        发送另一封邮件
                    </button>
                </div>
            </div>
        );
    }

    return (
        <div className="w-full max-w-md mx-auto">
            <div className="bg-[#112240] border border-[#233554] rounded-2xl p-6 md:p-8 relative overflow-hidden">
                {/* Decorative elements */}
                <div className="absolute top-0 right-0 w-32 h-32 bg-[#64FFDA] rounded-full filter blur-[80px] opacity-10 pointer-events-none"></div>
                <div className="absolute bottom-0 left-0 w-24 h-24 bg-purple-500 rounded-full filter blur-[60px] opacity-10 pointer-events-none"></div>

                <div className="relative">
                    {/* Header */}
                    <div className="text-center mb-6">
                        <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#64FFDA]/10 border border-[#64FFDA]/30 text-[#64FFDA] text-xs font-medium mb-4">
                            <Sparkles size={12} />
                            开启您的 AI 之旅
                        </div>
                        <h3 className="text-xl md:text-2xl font-bold text-white mb-2">
                            让我们保持联系 ✨
                        </h3>
                        <p className="text-slate-400 text-sm">
                            留下您的邮箱，我们会发送一封欢迎信并了解您的需求
                        </p>
                    </div>

                    {/* Form */}
                    <form onSubmit={handleSubmit} className="space-y-4">
                        <div className="relative">
                            <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                                <Mail className="w-5 h-5 text-slate-500" />
                            </div>
                            <input
                                type="email"
                                value={email}
                                onChange={(e) => {
                                    setEmail(e.target.value);
                                    if (status === 'error') {
                                        setStatus('idle');
                                        setMessage('');
                                    }
                                }}
                                placeholder="请输入您的邮箱地址"
                                className={`w-full pl-12 pr-4 py-4 bg-[#0A192F] border rounded-xl text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-[#64FFDA]/50 transition-all ${status === 'error'
                                    ? 'border-red-500/50 focus:ring-red-500/50'
                                    : 'border-[#233554] focus:border-[#64FFDA]'
                                    }`}
                                disabled={status === 'loading'}
                            />
                        </div>

                        {/* Error message */}
                        {status === 'error' && message && (
                            <p className="text-red-400 text-sm flex items-center gap-2">
                                <span className="w-1.5 h-1.5 rounded-full bg-red-400"></span>
                                {message}
                            </p>
                        )}

                        {/* Submit button */}
                        <button
                            type="submit"
                            disabled={status === 'loading'}
                            className={`w-full py-4 rounded-xl font-bold flex items-center justify-center gap-2 transition-all ${status === 'loading'
                                ? 'bg-[#64FFDA]/50 text-[#0A192F]/70 cursor-not-allowed'
                                : 'bg-[#64FFDA] text-[#0A192F] hover:bg-[#64FFDA]/90 hover:shadow-lg hover:shadow-[#64FFDA]/20'
                                }`}
                        >
                            {status === 'loading' ? (
                                <>
                                    <Loader2 className="w-5 h-5 animate-spin" />
                                    发送中...
                                </>
                            ) : (
                                <>
                                    <Send className="w-5 h-5" />
                                    发送欢迎邮件
                                </>
                            )}
                        </button>
                    </form>

                    {/* Privacy note */}
                    <p className="text-center text-slate-600 text-xs mt-4">
                        我们尊重您的隐私，不会发送垃圾邮件
                    </p>
                </div>
            </div>
        </div>
    );
};

export default EmailSubscribe;
