import { useState } from 'react';
import { useSearchParams, useNavigate, Link } from 'react-router-dom';
import { useLanguage } from '../context/LanguageContext';
import Footer from '../components/Footer';
import { API_HOST } from '../config';

function Register() {
    const [searchParams] = useSearchParams();
    const navigate = useNavigate();
    const { t } = useLanguage();
    const [email, setEmail] = useState('');
    const [name, setName] = useState('');
    const [surname, setSurname] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const selectedPlan = searchParams.get('plan') || 'starter';

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsLoading(true);
        setError('');

        try {
            // Generate a random ID and token (you might want to handle this differently)
            const id = Math.random().toString(36).substr(2, 9);
            const token = Math.random().toString(36).substr(2, 9);

            const response = await fetch(`${API_HOST}/api/v1/onboard/check-email`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    id,
                    name,
                    surname,
                    email,
                    token,
                    plan: selectedPlan,
                    status: true
                }),
            });

            if (!response.ok) {
                throw new Error('Registration failed');
            }

            // Navigate to registration success page instead of verify-email
            navigate('/registration-success');
        } catch (err) {
            setError(err.message);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className="relative min-h-screen bg-white">
            {/* Floating elements */}
            <div className="absolute inset-0 overflow-hidden pointer-events-none">
                <div className="absolute top-40 left-20 w-32 h-32 bg-brand-purple/10 rounded-full blur-3xl animate-pulse"></div>
                <div className="absolute bottom-40 right-20 w-40 h-40 bg-brand-pink/10 rounded-full blur-3xl animate-pulse delay-1000"></div>
            </div>

            <div className="max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-8 pt-32">
                {/* Header section */}
                <div className="text-center mb-16">
                    <h1 className="text-[80px] leading-tight font-light tracking-tight text-gray-900 relative inline-block">
                        {t('register.title')}
                        <div className="absolute -top-1 -right-1 w-2 h-2 bg-brand-purple rounded-full"></div>
                    </h1>
                    <p className="text-xl text-gray-500 max-w-2xl mx-auto mt-6">
                        {t('register.selectedPlan')}: <span className="text-brand-purple font-medium">{selectedPlan}</span>
                    </p>
                </div>

                {/* Registration Form */}
                <div className="max-w-md mx-auto">
                    <div className="bg-white rounded-2xl shadow-lg p-8">
                        {error && (
                            <div className="p-4 rounded-lg bg-red-50 text-red-600 text-sm mb-6">
                                {error}
                            </div>
                        )}

                        <form onSubmit={handleSubmit} className="space-y-6">
                            <div>
                                <label htmlFor="name" className="block text-sm text-gray-700 mb-2">
                                    {t('register.firstName')}
                                </label>
                                <input
                                    id="name"
                                    name="name"
                                    type="text"
                                    required
                                    value={name}
                                    onChange={(e) => setName(e.target.value)}
                                    placeholder={t('register.firstNamePlaceholder')}
                                    className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-purple focus:border-transparent"
                                />
                            </div>

                            <div>
                                <label htmlFor="surname" className="block text-sm text-gray-700 mb-2">
                                    {t('register.lastName')}
                                </label>
                                <input
                                    id="surname"
                                    name="surname"
                                    type="text"
                                    required
                                    value={surname}
                                    onChange={(e) => setSurname(e.target.value)}
                                    placeholder={t('register.lastNamePlaceholder')}
                                    className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-purple focus:border-transparent"
                                />
                            </div>

                            <div>
                                <label htmlFor="email" className="block text-sm text-gray-700 mb-2">
                                    {t('register.email')}
                                </label>
                                <input
                                    id="email"
                                    name="email"
                                    type="email"
                                    required
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                    placeholder={t('register.emailPlaceholder')}
                                    className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand-purple focus:border-transparent"
                                />
                            </div>

                            <button
                                type="submit"
                                disabled={isLoading}
                                className="w-full bg-black text-white rounded-full py-3 text-sm group hover:bg-brand-purple transition-colors duration-300 flex items-center justify-center gap-2 disabled:opacity-50 disabled:hover:bg-black"
                            >
                            {isLoading ? (
                                <span>{t('register.creating')}</span>
                            ) : (
                                <span className="flex items-center gap-2">
                                    {t('register.create')}
                                    <span className="transform group-hover:translate-x-1 transition-transform">→</span>
                                </span>
                            )}
                            </button>
                        </form>
                    </div>

                    <div className="mt-6 text-center">
                        <p className="text-sm text-gray-500">
                            {t('register.haveAccount')}{' '}
                            <Link to="/login" className="text-brand-purple hover:text-brand-purple/80 transition-colors">
                                {t('register.signIn')}
                            </Link>
                        </p>
                    </div>
                </div>
            </div>
            <Footer />
        </div>
    );
}

export default Register;
