'use client'

import { useState, useTransition } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { submitCateringInquiry } from '../actions'
import styles from './CateringPopup.module.css'

interface CateringPopupProps {
    isOpen: boolean;
    onClose: () => void;
    initialEventType?: string;
}

export default function CateringPopup({ isOpen, onClose, initialEventType = '' }: CateringPopupProps) {
    const [isPending, startTransition] = useTransition();
    const [isSuccess, setIsSuccess] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        setError(null);

        const formData = new FormData(event.currentTarget);

        startTransition(async () => {
            try {
                const result = await submitCateringInquiry(formData);
                if (result.success) {
                    setIsSuccess(true);
                    setTimeout(() => {
                        onClose();
                        setIsSuccess(false);
                    }, 3000);
                } else {
                    setError('Failed to submit inquiry. Please try again.');
                }
            } catch (err) {
                setError('Something went wrong. Please try again later.');
            }
        });
    }

    return (
        <AnimatePresence>
            {isOpen && (
                <motion.div
                    className={styles.overlay}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    onClick={(e) => e.target === e.currentTarget && onClose()}
                >
                    <motion.div
                        className={styles.popup}
                        initial={{ opacity: 0, scale: 0.9, y: 20 }}
                        animate={{ opacity: 1, scale: 1, y: 0 }}
                        exit={{ opacity: 0, scale: 0.9, y: 20 }}
                        transition={{ type: 'spring', damping: 25, stiffness: 300 }}
                    >
                        <button className={styles.closeButton} onClick={onClose}>✕</button>

                        <h2 className={styles.title}>Catering Inquiry</h2>
                        <p className={styles.subtitle}>Let us make your event unforgettable with authentic Turkish flavors.</p>

                        {isSuccess ? (
                            <motion.div
                                className={styles.successMessage}
                                initial={{ opacity: 0, y: 10 }}
                                animate={{ opacity: 1, y: 0 }}
                            >
                                Thank you! Your inquiry has been sent to hello@antalyarestaurant.ca. We will get back to you shortly.
                            </motion.div>
                        ) : (
                            <form className={styles.form} onSubmit={handleSubmit}>
                                <div className={styles.formGrid}>
                                    <div className={styles.inputGroup}>
                                        <label className={styles.label} htmlFor="name">Full Name</label>
                                        <input className={styles.input} type="text" id="name" name="name" required placeholder="Enter Name" />
                                    </div>

                                    <div className={styles.inputGroup}>
                                        <label className={styles.label} htmlFor="email">Email Address</label>
                                        <input className={styles.input} type="email" id="email" name="email" required placeholder="Enter Email" />
                                    </div>

                                    <div className={styles.inputGroup}>
                                        <label className={styles.label} htmlFor="phone">Phone Number</label>
                                        <input className={styles.input} type="tel" id="phone" name="phone" required placeholder="Enter Phone Number" />
                                    </div>

                                    <div className={styles.inputGroup}>
                                        <label className={styles.label} htmlFor="eventType">Event Type</label>
                                        <select className={styles.input} id="eventType" name="eventType" defaultValue={initialEventType} required>
                                            <option value="" disabled>Select Event Type</option>
                                            <option value="Corporate & Social Events">Corporate & Social Events</option>
                                            <option value="Family Gatherings & Weddings">Family Gatherings & Weddings</option>
                                            <option value="Birthday Party & Baby Shower">Birthday Party & Baby Shower</option>
                                            <option value="Other">Other Event</option>
                                        </select>
                                    </div>

                                    <div className={styles.inputGroup}>
                                        <label className={styles.label} htmlFor="date">Date of Event</label>
                                        <input className={styles.input} type="date" id="date" name="date" required />
                                    </div>

                                    <div className={styles.inputGroup}>
                                        <label className={styles.label} htmlFor="guests">Number of Guests</label>
                                        <input className={styles.input} type="number" id="guests" name="guests" required min="1" placeholder="Enter Number of Guests" />
                                    </div>

                                    <div className={`${styles.inputGroup} ${styles.fullWidth}`}>
                                        <label className={styles.label} htmlFor="message">Any Special Requests?</label>
                                        <textarea className={styles.textarea} id="message" name="message" placeholder="Enter Your Message..."></textarea>
                                    </div>

                                    <button
                                        className={styles.submitButton}
                                        type="submit"
                                        disabled={isPending}
                                    >
                                        {isPending ? 'Sending Inquiry...' : 'Submit Inquiry'}
                                    </button>
                                </div>
                                {error && <p style={{ color: 'red', fontSize: '0.85rem', textAlign: 'center' }}>{error}</p>}
                            </form>
                        )}
                    </motion.div>
                </motion.div>
            )}
        </AnimatePresence>
    )
}
