'use client'

import { useState, useEffect } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";

import Footer from "@/components/Footer/Footer";
import Image from "next/image";
import Link from "next/link";
import styles from "./contact.module.css";
import { motion } from "framer-motion";

interface FormErrors {
    name?: string;
    email?: string;
    phone?: string;
    date?: string;
    time?: string;
    captcha?: string;
}

export default function ContactContent() {
    const [email, setEmail] = useState("");

    useEffect(() => {
        const user = "hello";
        const domain = "antalyarestaurant.ca";
        setEmail(`${user}@${domain}`);
    }, []);

    const [formData, setFormData] = useState({
        name: "",
        email: "",
        phone: "",
        guests: "2 Guests",
        date: "",
        time: "",
        requests: "",
    });

    const [formErrors, setFormErrors] = useState<FormErrors>({});
    const [captchaToken, setCaptchaToken] = useState<string | null>(null);
    const [alert, setAlert] = useState({ show: false, type: "", message: "" });
    const [charCount, setCharCount] = useState(0);

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

        if (name === "requests") {
            setCharCount(value.length);
        }
    };

    const handleCaptchaChange = (token: string | null) => {
        setCaptchaToken(token);
    };

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

        const errors: FormErrors = {};
        if (!formData.name.trim()) errors.name = "Name is required.";
        if (!formData.email.trim()) errors.email = "Email is required.";
        if (!formData.phone.trim()) errors.phone = "Phone is required.";
        if (!formData.date.trim()) errors.date = "Date is required.";
        if (!formData.time.trim()) errors.time = "Time is required.";
        if (!captchaToken) errors.captcha = "Please verify the CAPTCHA.";

        setFormErrors(errors);
        if (Object.keys(errors).length > 0) return;

        const emailData = {
            name: formData.name,
            phone: formData.phone,
            email: formData.email,
            subject: `Table Reservation - ${formData.guests} on ${formData.date}`,
            message: `
                <strong>Reservation Details:</strong><br/>
                Name: ${formData.name}<br/>
                Email: ${formData.email}<br/>
                Phone: ${formData.phone}<br/>
                Guests: ${formData.guests}<br/>
                Date: ${formData.date}<br/>
                Time: ${formData.time}<br/><br/>
                <strong>Special Requests:</strong><br/>
                ${formData.requests || "None"}
            `,
            to: email,
            senderName: "Antalya Restaurant - Table Reservation",
            recaptchaToken: captchaToken,
        };

        try {
            const res = await axios.post(
                "https://mailserver.metatronnest.com/send",
                emailData,
                { headers: { "Content-Type": "application/json" } }
            );

            setAlert({
                show: true,
                type: "success",
                message: res?.data?.message || "Reservation request sent successfully! We'll contact you soon.",
            });

            setFormData({
                name: "",
                email: "",
                phone: "",
                guests: "2 Guests",
                date: "",
                time: "",
                requests: "",
            });
            setCaptchaToken(null);
            setFormErrors({});
            setCharCount(0);
        } catch (error) {
            setAlert({
                show: true,
                type: "danger",
                message: "Failed to send reservation request. Please try again later.",
            });
        }
    };

    useEffect(() => {
        if (alert.show) {
            const timer = setTimeout(() => {
                setAlert((prev) => ({ ...prev, show: false }));
            }, 5000);
            return () => clearTimeout(timer);
        }
    }, [alert.show]);

    return (
        <main className={styles.main}>


            <motion.section
                className={styles.hero}
                initial={{ opacity: 0, y: -20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.8 }}
            >
                <div className={styles.heroContent}>
                    <h1 className={styles.heroTitle}>Contact Us</h1>
                    <p className={styles.breadcrumb}>
                        <Link href="/">Home</Link> / Contact
                    </p>
                </div>
            </motion.section>

            <section className={styles.contactSection}>
                <motion.div
                    className={styles.container}
                    initial="hidden"
                    whileInView="visible"
                    viewport={{ once: true, margin: "-100px" }}
                    transition={{ staggerChildren: 0.3 }}
                >
                    {/* Left Side - Book a Table Form */}
                    <motion.div
                        className={styles.formBlock}
                        initial={{ opacity: 0, y: 30 }}
                        whileInView={{ opacity: 1, y: 0 }}
                        viewport={{ once: true }}
                        transition={{ duration: 0.8 }}
                    >
                        <div className={styles.smallHeading} style={{ display: 'flex', alignItems: 'center', justifyContent: 'start', gap: '10px' }}>
                            <Image src="/images/dinner.png" alt="Contact Section Decorative Dinner Icon" width={24} height={24} />
                            <span>ANTALYA</span>
                            <Image src="/images/eat.png" alt="Contact Section Decorative Cutlery Icon" width={24} height={24} />
                        </div>
                        <h2 className={styles.title}>Book a Table</h2>

                        <p className={styles.subtitle}>
                            Experience Antalya’s warm ambiance and rich culinary heritage in the heart of Ontario.
                            Our doors are open for dine-in, celebrations, and private gatherings.
                        </p>

                        {alert.show && (
                            <div className={`${styles.alert} ${styles[`alert${alert.type.charAt(0).toUpperCase() + alert.type.slice(1)}`]}`}>
                                {alert.message}
                            </div>
                        )}

                        <form className={styles.form} onSubmit={handleSubmit}>
                            <div className={styles.formRow}>
                                <div className={styles.formGroup}>
                                    <label htmlFor="name" className={styles.formLabel}>Name *</label>
                                    <input
                                        type="text"
                                        id="name"
                                        name="name"
                                        className={styles.input}
                                        placeholder="Your Full Name"
                                        value={formData.name}
                                        onChange={handleChange}
                                        required
                                    />
                                    {formErrors.name && <small className={styles.errorText}>{formErrors.name}</small>}
                                </div>

                                <div className={styles.formGroup}>
                                    <label htmlFor="email" className={styles.formLabel}>Email *</label>
                                    <input
                                        type="email"
                                        id="email"
                                        name="email"
                                        className={styles.input}
                                        placeholder="your@email.com"
                                        value={formData.email}
                                        onChange={handleChange}
                                        required
                                    />
                                    {formErrors.email && <small className={styles.errorText}>{formErrors.email}</small>}
                                </div>
                            </div>

                            <div className={styles.formRow}>
                                <div className={styles.formGroup}>
                                    <label htmlFor="phone" className={styles.formLabel}>Phone *</label>
                                    <input
                                        type="tel"
                                        id="phone"
                                        name="phone"
                                        className={styles.input}
                                        placeholder="(519) 000-0000"
                                        value={formData.phone}
                                        onChange={handleChange}
                                        required
                                    />
                                    {formErrors.phone && <small className={styles.errorText}>{formErrors.phone}</small>}
                                </div>

                                <div className={styles.formGroup}>
                                    <label htmlFor="guests" className={styles.formLabel}>Guests</label>
                                    <select
                                        id="guests"
                                        name="guests"
                                        className={styles.input}
                                        value={formData.guests}
                                        onChange={handleChange}
                                    >
                                        <option>1 Guest</option>
                                        <option>2 Guests</option>
                                        <option>3 Guests</option>
                                        <option>4 Guests</option>
                                        <option>5 Guests</option>
                                        <option>6+ Guests</option>
                                    </select>
                                </div>
                            </div>

                            <div className={styles.formRow}>
                                <div className={styles.formGroup}>
                                    <label htmlFor="date" className={styles.formLabel}>Date *</label>
                                    <input
                                        type="date"
                                        id="date"
                                        name="date"
                                        className={styles.input}
                                        value={formData.date}
                                        onChange={handleChange}
                                        required
                                    />
                                    {formErrors.date && <small className={styles.errorText}>{formErrors.date}</small>}
                                </div>

                                <div className={styles.formGroup}>
                                    <label htmlFor="time" className={styles.formLabel}>Time *</label>
                                    <input
                                        type="time"
                                        id="time"
                                        name="time"
                                        className={styles.input}
                                        value={formData.time}
                                        onChange={handleChange}
                                        required
                                    />
                                    {formErrors.time && <small className={styles.errorText}>{formErrors.time}</small>}
                                </div>
                            </div>

                            <div className={styles.formGroup}>
                                <label htmlFor="requests" className={styles.formLabel}>Special Requests</label>
                                <textarea
                                    id="requests"
                                    name="requests"
                                    className={styles.textarea}
                                    placeholder="Any special dietary requirements or requests..."
                                    rows={4}
                                    maxLength={500}
                                    value={formData.requests}
                                    onChange={handleChange}
                                ></textarea>
                                <span className={styles.charCount}>{charCount}/500 characters</span>
                            </div>

                            <div className={styles.recaptchaWrapper}>
                                <ReCAPTCHA
                                    sitekey="6Lckq9MrAAAAABjBD9rQYm19BMGFFWiwb9mPiw2K"
                                    onChange={handleCaptchaChange}
                                />
                                {formErrors.captcha && <small className={styles.errorText}>{formErrors.captcha}</small>}
                            </div>

                            <button type="submit" className={styles.submitButton}>
                                Reserve Table
                            </button>
                        </form>
                    </motion.div>

                    {/* Right Side - Location Info & Map */}
                    <motion.div
                        className={styles.infoBlock}
                        initial={{ opacity: 0, y: 30 }}
                        whileInView={{ opacity: 1, y: 0 }}
                        viewport={{ once: true }}
                        transition={{ duration: 0.8 }}
                    >
                        <div className={styles.locationCard}>
                            <div className={styles.iconWrapper}>
                                <svg className={styles.icon} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                </svg>
                            </div>
                            <div className={styles.locationInfo}>
                                <h3 className={styles.locationTitle}>Call Us</h3>

                                <div className={styles.phoneFlex}>
                                    <a href="tel:5195816363" className={styles.locationSubtitle}>
                                        Kitchener : 519-581-6363
                                    </a>

                                    <a href="tel:2893139838" className={styles.locationSubtitle}>
                                        Burlington : 289-313-9838
                                    </a>
                                </div>
                            </div>


                        </div>
                        {/* Location Cards */}


                        <div className={styles.locationCard}>
                            <div className={styles.iconWrapper}>
                                <svg className={styles.icon} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                                </svg>
                            </div>
                            <div className={styles.locationInfo}>
                                <h3 className={styles.locationTitle}>Contact Us</h3>

                                <a href="mailto:hello@antalyarestaurant.ca" className={styles.locationSubtitle}>
                                    hello@antalyarestaurant.ca
                                </a>
                            </div>

                        </div>

                        <div className={styles.locationCard}>
                            <div className={styles.iconWrapper}>
                                <svg className={styles.icon} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                                </svg>
                            </div>
                            <div className={styles.locationInfo}>
                                <h3 className={styles.locationTitle}>Location</h3>
                                <p className={styles.locationSubtitle}>1187 Fischer-Hallman Rd #435, Kitchener, ON N2E 4H9</p>
                                <p className={styles.locationSubtitle}>
                                    1860 Appleby Line, Burlington, ON L7L 7H7
                                </p>
                            </div>
                        </div>



                        {/* Map */}
                        <div className={styles.mapContainer}>
                            <iframe
                                src="https://www.google.com/maps/embed?pb=!1m28!1m12!1m3!1d11603.157684992676!2d-79.89907629708574!3d43.417739917762866!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!4m13!3e0!4m5!1s0x882bf4df1b8fa34d%3A0x9cb41f8ef1c4e9ac!2s1187%20Fischer-Hallman%20Rd%20%23435%2C%20Kitchener%2C%20ON%20N2E%204H9%2C%20Canada!3m2!1d43.4477606!2d-80.4809184!4m5!1s0x882b5fcd79165b0f%3A0x9d76a7bc4fd95533!2s1860%20Appleby%20Line%2C%20Burlington%2C%20ON%20L7L%207H7%2C%20Canada!3m2!1d43.3870284!2d-79.7771573!5e0!3m2!1sen!2sca!4v1700000123456!5m2!1sen!2sca"
                                width="100%"
                                height="900"
                                style={{ border: 0 }}
                                allowFullScreen
                                loading="lazy"
                                referrerPolicy="no-referrer-when-downgrade"
                            ></iframe>
                        </div>

                    </motion.div>
                </motion.div>
            </section>

            <Footer />
        </main>
    );
}
