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

function Payment({ pricingData }) {
    const [searchParams] = useSearchParams();
    const { t } = useLanguage();
    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">
            {/* Technical grid background */}
            <div className="fixed inset-0 technical-grid opacity-50 pointer-events-none"></div>

            <div className="max-w-[1600px] mx-auto px-8 sm:px-12 lg:px-16 pt-32">
                {/* Header section */}
                <div className="grid-layout mb-16">
                    <div className="col-span-12 md:col-span-8">
                        <h1 className="brutalist-heading relative">
                            Complete Setup
                            <div className="absolute -right-8 -top-8 w-16 h-16">
                                <div className="geometric-shape diamond w-full h-full bg-black"></div>
                            </div>
                        </h1>
                        <p className="monospace text-xl md:text-2xl font-medium tracking-tight max-w-2xl">
                            Selected plan: <span className="uppercase font-bold">{selectedPlan}</span>
                        </p>
                    </div>
                </div>

                <div className="geometric-divider mb-16"></div>

                {/* Content */}
                <div className="grid-layout">
                    <div className="col-span-12 md:col-span-6 lg:col-span-4">
                        <div className="brutalist-card">
                            {message && (
                                <div className="p-4 border-2 border-black bg-yellow-100 monospace">
                                    {message}
                                </div>
                            )}
                            <div className="p-6 space-y-8">
                                <div className="space-y-4">
                                    <div className="flex justify-between items-center">
                                        <span className="monospace uppercase text-sm font-black">Plan</span>
                                        <span className="monospace uppercase font-bold">{selectedPlan}</span>
                                    </div>
                                    <div className="section-divider"></div>
                                    <div className="flex justify-between items-center">
                                        <span className="monospace uppercase text-sm font-black">Amount</span>
                                        <span className="monospace font-bold">
                                            ${amount}.00 / {billingCycle === 'yearly' ? 'year' : 'month'}
                                        </span>
                                    </div>
                                    <div className="section-divider"></div>
                                    <div className="flex justify-between items-center">
                                        <span className="monospace uppercase text-sm font-black">Trial Period</span>
                                        <span className="monospace font-bold">14 days free</span>
                                    </div>
                                </div>

                                <form onSubmit={handleCheckout} className="mt-8">
                                    <button
                                        type="submit"
                                        disabled={isLoading}
                                        className="brutalist-button w-full disabled:opacity-50"
                                    >
                                        {isLoading ? (
                                            <span className="monospace">Processing...</span>
                                        ) : (
                                            <span>Proceed to checkout →</span>
                                        )}
                                    </button>
                                </form>

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

            <Footer />
        </div>
    );
}

export default Payment; 