import { useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import PropTypes from 'prop-types';
import Footer from '../components/Footer';
import { API_HOST } from '../config';

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

    const selectedPlan = searchParams.get('plan') || 'starter';
    const billingCycle = searchParams.get('billing') || 'monthly';
    const email = searchParams.get('email');

    // Find the selected plan details from pricingData
    const planDetails = pricingData?.find(plan => 
        plan.name.toLowerCase() === selectedPlan.toLowerCase()
    );

    const amount = planDetails ? (
        billingCycle === 'yearly' 
            ? planDetails.prices.yearly 
            : planDetails.prices.monthly
    ) : 0;

    const handleCheckout = async (e) => {
        e.preventDefault();
        setIsLoading(true);
        try {
            const formData = new FormData();
            formData.append('priceId', billingCycle === 'yearly' 
                ? planDetails?.prices.yearlyPriceId 
                : planDetails?.prices.monthlyPriceId
            );
            formData.append('email', email);

            const response = await fetch(`${API_HOST}/api/v1/onboard/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');
            }

            const { url } = await response.json();
            window.location.href = url;

        } catch (error) {
            setMessage(error.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">
                        Complete Setup
                        <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">
                        Selected plan: <span className="text-brand-purple font-medium uppercase">{selectedPlan}</span>
                    </p>
                </div>

                {/* Content */}
                <div className="max-w-md mx-auto">
                    <div className="bg-white rounded-2xl shadow-lg p-8">
                        {message && (
                            <div className="p-4 rounded-lg bg-yellow-50 text-yellow-800 text-sm mb-6">
                                {message}
                            </div>
                        )}
                        <div className="space-y-6">
                            <div className="space-y-4">
                                <div className="flex justify-between items-center">
                                    <span className="text-sm text-gray-600">Plan</span>
                                    <span className="font-medium text-gray-900 uppercase">{selectedPlan}</span>
                                </div>
                                <div className="h-px bg-gray-100"></div>
                                <div className="flex justify-between items-center">
                                    <span className="text-sm text-gray-600">Amount</span>
                                    <span className="font-medium text-gray-900">
                                        ${amount}.00 / {billingCycle === 'yearly' ? 'year' : 'month'}
                                    </span>
                                </div>
                                <div className="h-px bg-gray-100"></div>
                                <div className="flex justify-between items-center">
                                    <span className="text-sm text-gray-600">Trial Period</span>
                                    <span className="font-medium text-gray-900">14 days free</span>
                                </div>
                            </div>

                            <form onSubmit={handleCheckout}>
                                <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>Processing...</span>
                                    ) : (
                                        <span className="flex items-center gap-2">
                                            Proceed to checkout
                                            <span className="transform group-hover:translate-x-1 transition-transform">→</span>
                                        </span>
                                    )}
                                </button>
                            </form>

                            <div className="text-center">
                                <p className="text-sm text-gray-500">
                                    Secure payment powered by Stripe
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <Footer />
        </div>
    );
}

Payment.propTypes = {
    pricingData: PropTypes.arrayOf(
        PropTypes.shape({
            name: PropTypes.string.isRequired,
            prices: PropTypes.shape({
                monthly: PropTypes.number.isRequired,
                yearly: PropTypes.number.isRequired,
                monthlyPriceId: PropTypes.string.isRequired,
                yearlyPriceId: PropTypes.string.isRequired
            }).isRequired
        })
    )
};

Payment.defaultProps = {
    pricingData: []
};

export default Payment;
