'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { loadStripe } from '@stripe/stripe-js';
// @ts-expect-error PaystackPop is not typed
import PaystackPop from '@paystack/inline-js';
import { useRouter } from 'next/navigation';
import CloseIcon from './icons/close';

const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);

interface GiftModalProps {
    isOpen: boolean;
    onClose: () => void;
}

export default function GiftModal({ isOpen, onClose }: GiftModalProps) {
    const [formData, setFormData] = useState({
        name: '',
        email: '',
        message: '',
        amount: '',
        currency: 'NGN'
    });
    const [isLoading, setIsLoading] = useState(false);
    const router = useRouter();

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        setFormData(prev => ({
            ...prev,
            [e.target.name]: e.target.value
        }));
    };

    const initializePaystack = async () => {
        try {
            const response = await fetch('/api/initialize-paystack', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    email: formData.email,
                    amount: parseFloat(formData.amount),
                    name: formData.name,
                }),
            });

            const { data } = await response.json();

            // Store form data in localStorage
            localStorage.setItem('giftData', JSON.stringify({
                name: formData.name,
                email: formData.email,
                message: formData.message,
                amount: parseFloat(formData.amount),
                currency: formData.currency
            }));

            const paystack = new PaystackPop();
            paystack.newTransaction({
                key: process.env.NEXT_PUBLIC_PAYSTACK_PUBLIC_KEY!,
                ref: data.reference,
                email: formData.email,
                amount: parseFloat(formData.amount) * 100,
                onSuccess: () => {
                    router.push(`/success?reference=${data.reference}`);
                },
                onCancel: () => {
                    localStorage.removeItem('giftData');
                    setIsLoading(false);
                },
            });
        } catch (error) {
            console.error('Error:', error);
            localStorage.removeItem('giftData');
            setIsLoading(false);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsLoading(true);

        if (formData.currency === 'NGN') {
            await initializePaystack();
            return;
        }

        try {
            // Store form data in localStorage before initiating Stripe checkout
            localStorage.setItem('giftData', JSON.stringify({
                name: formData.name,
                email: formData.email,
                message: formData.message,
                amount: parseFloat(formData.amount),
                currency: formData.currency
            }));

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

            if (!response.ok) {
                throw new Error('Failed to create checkout session');
            }

            const { sessionId } = await response.json();
            const stripe = await stripePromise;

            if (stripe) {
                const { error } = await stripe.redirectToCheckout({
                    sessionId,
                });

                if (error) {
                    console.error('Error:', error);
                    localStorage.removeItem('giftData');
                }
            }
        } catch (error) {
            console.error('Error:', error);
            localStorage.removeItem('giftData');
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <AnimatePresence>
            {isOpen && (
                <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
                    onClick={onClose}
                >
                    <motion.div
                        initial={{ scale: 0.95, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        exit={{ scale: 0.95, opacity: 0 }}
                        className="bg-white rounded-lg p-6 max-w-md w-full relative"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <h2 className="text-coral font-script text-3xl text-center my-6">Be a part of Our Journey</h2>
                        <button onClick={onClose} className='absolute top-0 right-0 pr-1 pt-1 pl-1 pb-1 rounded-bl-2xl rounded-tr-lg bg-coral hover:bg-coral/80 transition-colors'><CloseIcon className='w-6 h-6' /></button>
                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div>
                                {/* <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Your Name
                                </label> */}
                                <input
                                    type="text"
                                    name="name"
                                    value={formData.name}
                                    placeholder='Your name'
                                    onChange={handleChange}
                                    className="w-full bg-transparent border-b border-[#222]/20 py-2 px-1 focus:outline-none focus:border-coral"
                                    required
                                />
                            </div>

                            <div>
                                {/* <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Your Email
                                </label> */}
                                <input
                                    type="email"
                                    name="email"
                                    value={formData.email}
                                    onChange={handleChange}
                                    placeholder="Your email"
                                    className="w-full bg-transparent border-b border-[#222]/20 py-2 px-1 focus:outline-none focus:border-coral"
                                    required
                                />
                            </div>

                            <div className="grid grid-cols-12 gap-4">
                                <div className="col-span-5">
                                    <select
                                        name="currency"
                                        value={formData.currency}
                                        onChange={handleChange}
                                        className="w-full bg-transparent border-b border-[#222]/20 py-2 px-1 pt-[14px] focus:outline-none focus:border-coral"
                                    >
                                        <option value="NGN">Nigerian Naira (NGN)</option>
                                        <option value="GBP">British Pound (GBP)</option>
                                        <option value="USD">United States Dollar (USD)</option>
                                    </select>
                                </div>

                                <div className="col-span-7">
                                    <input
                                        type="number"
                                        name="amount"
                                        value={formData.amount}
                                        onChange={handleChange}
                                        placeholder='Amount'
                                        className="w-full bg-transparent border-b border-[#222]/20 py-2 px-1 focus:outline-none focus:border-coral"
                                        min="1"
                                        required
                                    />
                                </div>
                            </div>

                            <div>
                                {/* <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Message (Optional)
                                </label> */}
                                <textarea
                                    name="message"
                                    value={formData.message}
                                    placeholder='Message (Optional)'
                                    onChange={handleChange}
                                    className="w-full bg-transparent border-b border-[#222]/20 py-2 px-1 focus:outline-none focus:border-coral"
                                    rows={3}
                                />
                            </div>

                            <button
                                type="submit"
                                disabled={isLoading}
                                className="btn-outline-dark w-full"
                            >
                                {isLoading ? 'Processing...' : 'Confirm'}
                            </button>
                        </form>
                    </motion.div>
                </motion.div>
            )}
        </AnimatePresence>
    );
} 