'use client';

import Checkout from '@/components/Checkout';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState, Suspense } from 'react';

function CheckoutContent() {
    const router = useRouter();
    const searchParams = useSearchParams();
    const planId = searchParams.get('plan') || 'pro';

    const [plan, setPlan] = useState<{ id: string, displayName: string, price: number } | null>(null);

    useEffect(() => {
        fetch('/api/plans', { cache: 'no-store' })
            .then(res => res.json())
            .then(data => {
                const found = data.find((p: any) => p.id === planId);
                if (found) {
                    setPlan(found);
                } else {
                    setPlan(data.find((p: any) => p.id === 'pro') || { id: 'pro', displayName: 'Auteur Pro', price: 12.00 });
                }
            })
            .catch(err => {
                console.error(err);
                setPlan({ id: 'pro', displayName: 'Auteur Pro', price: 12.00 });
            });
    }, [planId]);

    const handleComplete = async () => {
        if (plan) {
            try {
                await fetch('/api/user/profile', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ planId: plan.id })
                });
                // Force a full reload to update user context in providers
                window.location.href = '/dashboard';
            } catch (err) {
                console.error('Failed to update plan', err);
                router.push('/dashboard');
            }
        } else {
            router.push('/dashboard');
        }
    };

    if (!plan) return <div className="min-h-screen bg-[#eef2ff] flex items-center justify-center p-8">Chargement...</div>;

    return (
        <Checkout
            plan={plan}
            onComplete={handleComplete}
            onCancel={() => router.push('/pricing')}
        />
    );
}

export default function CheckoutPage() {
    return (
        <Suspense fallback={<div className="min-h-screen bg-[#eef2ff] flex items-center justify-center p-8">Chargement...</div>}>
            <CheckoutContent />
        </Suspense>
    );
}
