"use client";
import { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';

export default function SuccessContent() {
    const [isLoading, setIsLoading] = useState(true);
    const searchParams = useSearchParams();

    useEffect(() => {
        const sendEmails = async () => {
            try {
                const sessionId = searchParams.get('session_id');
                const reference = searchParams.get('reference');

                if (!sessionId && !reference) return;

                // Retrieve session data from localStorage
                const giftData = JSON.parse(localStorage.getItem('giftData') || '{}');

                if (reference) {
                    // Verify Paystack payment
                    const verifyResponse = await fetch('/api/verify-paystack', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ reference }),
                    });

                    if (!verifyResponse.ok) {
                        throw new Error('Payment verification failed');
                    }
                }

                // Send emails
                await fetch('/api/send-gift-emails', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        ...giftData,
                        sessionId: sessionId || reference,
                    }),
                });

                // Clear the stored data
                localStorage.removeItem('giftData');
            } catch (error) {
                console.error('Error:', error);
            } finally {
                setIsLoading(false);
            }
        };

        sendEmails();
    }, [searchParams]);

    if (isLoading) {
        return <div className="min-h-screen flex items-center justify-center">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-coral"></div>
        </div>;
    }

    return (<div className="min-h-screen flex items-center justify-center p-4">
        <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-center space-y-6"
        >
            <h1 className="text-coral font-script text-4xl md:text-5xl">Thank You!</h1>
            <p className="text-[1.25rem] leading-8">
                Your generous gift means the world to us. We are truly grateful for your support.
            </p>
            <Link href="/" className="btn-outline-dark inline-block">
                Return Home
            </Link>
        </motion.div>
    </div>
    );
}