'use client';

import React, { useState, useEffect } from 'react';
import Pricing from '@/components/Pricing';
import { useRouter } from 'next/navigation';
import { useAuthContext } from '@/providers/AuthProvider';

export default function PricingPage() {
    const router = useRouter();
    const { user } = useAuthContext();

    const [plans, setPlans] = useState([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        fetch('/api/plans', { cache: 'no-store' })
            .then(res => res.json())
            .then(data => {
                setPlans(data);
                setIsLoading(false);
            })
            .catch(err => {
                console.error(err);
                setIsLoading(false);
            });
    }, []);

    return (
        <Pricing
            plans={plans}
            isLoading={isLoading}
            currentPlan={user?.planId || 'free'}
            onBack={() => router.push(user ? '/dashboard' : '/')}
            onSelectPlan={async (id) => {
                if (!user) {
                    router.push('/login');
                    return;
                }

                try {
                    const response = await fetch('/api/checkout', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ planId: id })
                    });

                    const data = await response.json();
                    if (data.url) {
                        window.location.href = data.url;
                    }
                } catch (err) {
                    console.error('Checkout error:', err);
                }
            }}
        />
    );
}
