import { useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useLanguage } from '../context/LanguageContext';

function Payment() {
    const [searchParams] = useSearchParams();
    const { t } = useLanguage();
    const [message, setMessage] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    const selectedPlan = searchParams.get('plan') || 'starter';
    const planAmounts = {
        starter: 29,
        professional: 99,
        business: 249
    };

    const handleCheckout = async (e) => {
        e.preventDefault();
        setIsLoading(true);
        try {
            // Step 1: Create payment intent through your backend
            const formData = new FormData();
            formData.append('lookup_key', `${selectedPlan}_monthly`);

            // Get email from URL parameters
            const userEmail = searchParams.get('email');
            if (!userEmail) {
                throw new Error('Email not found. Please try registering again.');
            }
            formData.append('email', userEmail);

            const response = await fetch('http://192.168.1.35:8080/api/v1/create-checkout-session', {
                method: 'POST',
                body: formData,
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || 'Failed to create checkout session');
            }

            // Step 2: Get the sessionId from your backend
            const { sessionId, url } = await response.json();

            // Step 3: Redirect to Stripe checkout using the returned URL
            window.location.href = url;

        } catch (error) {
            setMessage(error.message);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className="min-h-screen flex items-center justify-center px-4 relative">
            {/* Background elements */}
            <div className="absolute inset-0 pointer-events-none overflow-hidden">
                <div className="absolute top-1/4 left-1/4 w-64 h-64 bg-brand-purple/10 rounded-full blur-3xl transform -translate-x-1/2 -translate-y-1/2"></div>
                <div className="absolute bottom-1/4 right-1/4 w-64 h-64 bg-brand-pink/10 rounded-full blur-3xl transform translate-x-1/2 translate-y-1/2"></div>
            </div>

            <div className="w-full max-w-md">
                <div className="bg-white/80 backdrop-blur-sm shadow-xl rounded-3xl p-8">
                    <div className="text-center mb-8">
                        <h2 className="text-[40px] font-light tracking-tight text-gray-900 relative inline-block">
                            Complete Setup
                            <span className="absolute -top-1 -right-1 w-2 h-2 bg-brand-purple rounded-full"></span>
                        </h2>
                        <p className="mt-2 text-sm text-gray-600">
                            Selected plan: <span className="font-medium capitalize">{selectedPlan}</span>
                        </p>
                    </div>

                    {message ? (
                        <div className="bg-yellow-50 rounded-2xl p-6">
                            <p className="text-yellow-800">{message}</p>
                        </div>
                    ) : (
                        <div className="space-y-8">
                            <div className="bg-gray-50 rounded-2xl p-6">
                                <div className="flex justify-between items-center mb-4">
                                    <span className="text-gray-600">Plan</span>
                                    <span className="font-medium capitalize">{selectedPlan}</span>
                                </div>
                                <div className="flex justify-between items-center mb-4">
                                    <span className="text-gray-600">Amount</span>
                                    <span className="font-medium">${planAmounts[selectedPlan]}.00 / month</span>
                                </div>
                                <div className="flex justify-between items-center">
                                    <span className="text-gray-600">Trial Period</span>
                                    <span className="text-brand-purple font-medium">14 days free</span>
                                </div>
                            </div>
                            <form onSubmit={handleCheckout}>
                                <input type="hidden" name="lookup_key" value={`${selectedPlan}_monthly`} />
                                <button
                                    type="submit"
                                    disabled={isLoading}
                                    className="w-full rounded-full bg-brand-purple px-6 py-4 text-sm font-semibold text-white shadow-sm hover:bg-brand-purple/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-purple transition-all flex items-center justify-center gap-2 disabled:opacity-70"
                                >
                                    {isLoading ? (
                                        <>
                                            <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                            <span>Processing...</span>
                                        </>
                                    ) : (
                                        <>
                                            <span>Proceed to checkout</span>
                                            <span className="transform group-hover:translate-x-1 transition-transform">→</span>
                                        </>
                                    )}
                                </button>
                            </form>
                        </div>
                    )}

                    <p className="mt-4 text-center text-sm text-gray-500">
                        Secure payment powered by Stripe
                    </p>
                </div>
            </div>
        </div>
    );
}

export default Payment; 