"use client";

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

const HomeContactOne = () => {
    const [formData, setFormData] = useState({
        name: "",
        phone: "",
        email: "",
        service: "",
        message: "",
    });

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

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

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

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

        const errors: any = {};
        if (!formData.name.trim()) errors.name = "Name is required.";
        if (!formData.phone.trim()) errors.phone = "Phone is required.";
        if (!formData.email.trim()) errors.email = "Email is required.";
        if (!formData.service.trim()) errors.service = "Please select a service.";
        if (!formData.message.trim()) errors.message = "Message is required.";
        if (!captchaToken) errors.captcha = "Please verify the CAPTCHA.";

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

        const emailData = {
            ...formData,
            message: `Service: ${formData.service}<br /><br />Message: ${formData.message}`,
            to: "info@metatroncubesolutions.com",
            senderName: "Metatroncube Home Contact",
            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: "Thank you! Your message has been sent successfully.",
            });

            setFormData({
                name: "",
                phone: "",
                email: "",
                service: "",
                message: "",
            });
            setCaptchaToken(null);
            setFormErrors({});
        } catch (error) {
            console.error("❌ Error sending email:", error);
            setAlert({
                show: true,
                type: "danger",
                message: "Failed to send message. Please try again later.",
            });
        }
    };

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

    return (
        <section className="home-contact-one">
            <div
                className="home-contact-one__bg"
                style={{ backgroundImage: 'url(/assets/images/home/bg-without.webp)' }}
            ></div>
            <div className="container">
                <div className="row">
                    <div className="col-xl-6 d-flex align-items-center justify-content-center">
                        <div className="home-contact__card" style={{ marginBottom: '10px' }}>
                            <div className="home-contact__card__content">
                                <ul className="home-contact__card__list">
                                    <li>
                                        <span className="fa fa-phone"></span>
                                        <div className="pl-5">
                                            <h3 className="home-contact__card__list__title">Get Contact Now</h3>
                                            <p className="home-contact__card__list__text">
                                                <a href="tel:+16476797651">+1-647-679-7651</a>
                                            </p>
                                        </div>
                                        <div className="home-contact__card__list__shape"></div>
                                    </li>
                                    <li>
                                        <span className="fa-solid fa-envelope"></span>
                                        <div className="pl-5">
                                            <h3 className="home-contact__card__list__title">Sent Email</h3>
                                            <p className="home-contact__card__list__text">
                                                <a href="mailto:info@metatroncubesolutions.com">info@metatroncubesolutions.com</a>
                                            </p>
                                        </div>
                                        <div className="home-contact__card__list__shape"></div>
                                    </li>
                                    <li>
                                        <span className="fa-solid fa-location-dot"></span>
                                        <div className="pl-5">
                                            <h3 className="home-contact__card__list__title">Location</h3>
                                            <p className="home-contact__card__list__text">Canada</p>
                                        </div>
                                        <div className="home-contact__card__list__shape"></div>
                                    </li>
                                </ul>
                            </div>
                            <div className="home-contact__card__shape-one">
                            </div>
                            <img
                                src="/assets/images/home/7/contact.webp"
                                alt="Expect a personalized reply within one business day."
                                className="home-contact__card__shape-two"
                            />
                        </div>
                    </div>
                    <div className="col-xl-6">
                        <div className="home-contact-form-container-global">
                            <form
                                className="appointment__form contact-form-validated form-one"
                                onSubmit={handleSubmit}
                                noValidate
                            >
                                <div className="appointment__form__top">
                                    <div className="appointment__form__title">
                                        <div className="sec-title">
                                            <div className="sec-title__shape"></div>
                                            <h6 className="sec-title__tagline">CONTACT US</h6>
                                            <h3 className="sec-title__title">Drop us a <span className='inner-text'>Line. </span></h3>
                                        </div>
                                    </div>
                                </div>

                                {alert.show && (
                                    <div className={`alert alert-${alert.type === 'danger' ? 'danger' : 'success'} mb-4`} style={{ padding: '15px', borderRadius: '12px' }}>
                                        {alert.message}
                                    </div>
                                )}

                                <div className="form-one__group">
                                    <div className="mb-20">
                                        <label htmlFor="name" className="form-label-custom-global">Full Name</label>
                                        <input
                                            id="name"
                                            type="text"
                                            name="name"
                                            placeholder="Full Name"
                                            value={formData.name}
                                            onChange={handleChange}
                                            className="form-input-custom-global"
                                            suppressHydrationWarning={true}
                                        />
                                        {formErrors.name && <small className="text-danger">{formErrors.name}</small>}
                                    </div>
                                    <div className="mb-20">
                                        <label htmlFor="email" className="form-label-custom-global">Email Address</label>
                                        <input
                                            id="email"
                                            type="email"
                                            name="email"
                                            placeholder="Email Address"
                                            value={formData.email}
                                            onChange={handleChange}
                                            className="form-input-custom-global"
                                            suppressHydrationWarning={true}
                                        />
                                        {formErrors.email && <small className="text-danger">{formErrors.email}</small>}
                                    </div>
                                    <div className="mb-20">
                                        <label htmlFor="phone" className="form-label-custom-global">Phone Number</label>
                                        <input
                                            id="phone"
                                            type="text"
                                            name="phone"
                                            placeholder="Phone Number"
                                            value={formData.phone}
                                            onChange={handleChange}
                                            className="form-input-custom-global"
                                            suppressHydrationWarning={true}
                                        />
                                        {formErrors.phone && <small className="text-danger">{formErrors.phone}</small>}
                                    </div>
                                    <div className="mb-20">
                                        <label htmlFor="service" className="form-label-custom-global">Select Service</label>
                                        <select
                                            name="service"
                                            id="service"
                                            value={formData.service}
                                            onChange={handleChange}
                                            className="form-select-custom-styled-global"
                                            suppressHydrationWarning={true}
                                        >
                                            <option value="">Select Service</option>
                                            <option value="Website Development">Website Development</option>
                                            <option value="Mobile Application Development">Mobile Application Development</option>
                                            <option value="Graphic Designing">Graphic Designing</option>
                                            <option value="UI / UX Designing">UI / UX Designing</option>
                                            <option value="SEO & Content Writing">SEO & Content Writing</option>
                                            <option value="Digital Marketing">Digital Marketing</option>
                                            <option value="ERP Development & Implementation">ERP Development & Implementation</option>
                                        </select>
                                        {formErrors.service && <small className="text-danger">{formErrors.service}</small>}
                                    </div>
                                    <div className="form-one__control--full mb-20">
                                        <label htmlFor="message" className="form-label-custom-global">Write Message</label>
                                        <textarea
                                            id="message"
                                            name="message"
                                            placeholder="Write Message"
                                            value={formData.message}
                                            onChange={handleChange}
                                            rows={4}
                                            className="form-textarea-custom-global"
                                            suppressHydrationWarning={true}
                                        ></textarea>
                                        {formErrors.message && <small className="text-danger">{formErrors.message}</small>}
                                    </div>

                                    <div className="form-one__control--full mb-4">
                                        <ReCAPTCHA
                                            sitekey="6LekfpwrAAAAAOTwuP1d2gg-Fv9UEsAjE2gjOQJl"
                                            onChange={handleCaptchaChange}
                                        />
                                        {formErrors.captcha && <small className="text-danger">{formErrors.captcha}</small>}
                                    </div>

                                    <div className="form-one__control--full">
                                        <button type="submit" className="submit-btn-custom-global" suppressHydrationWarning={true}>
                                            SEND A MESSAGE
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </section >
    );
};

export default HomeContactOne;
