"use client";
import React from "react";
import { useState, useEffect } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";
import { FormField } from "../../utils/commonFunction.utils";
import LandAcknowledgement from "@/components/LandAcknowledgement"
import Section1 from "@/components/Section1"



const ContactSection = () => {

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    subject: "",
    message: "",

  });

  const [captchaToken, setCaptchaToken] = useState(null);
  const [alert, setAlert] = useState({
    show: false,
    type: "",
    message: "",
  });

  const [formErrors, setFormErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleCaptchaChange = (token) => {
    setCaptchaToken(token);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Form submitted", formData);

    const errors = {};
    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 number is required.";
    if (!formData.subject.trim()) errors.subject = "Subject is required";
    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) {
      console.warn("Validation errors:", errors);
      return;
    }

    const emailData = {
      ...formData,
      message: `Message: ${formData.message}`,
      to: "info@waterloomurugantemple.ca",
      senderName: "Murugan Temple Waterloo",
      recaptchaToken: captchaToken,
    };

    console.log("Sending email with data:", emailData);

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

      console.log("Email sent response:", res?.data);

      setAlert({
        show: true,
        type: "success",
        message: res?.data?.message || "Message sent successfully!",
      });

      setFormData({
        name: "",
        email: "",
        phone: "",
        subject: "",
        message: "",
      });
      setCaptchaToken(null);
      setFormErrors({});
    } catch (error) {
      console.error("Email sending failed:", error);

      setAlert({
        show: true,
        type: "danger",
        message: "Failed to send message. Please try again later.",
      });
    }
  };


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

  return (
    <>
      <Section1 />
      <LandAcknowledgement />
      <div className="space">
        <div className="container">
          <div className="map-sec">
            <iframe loading="lazy" src="https://maps.google.com/maps?q=P.O.Box%202503%2C%20Kitchener%20RPO%20Hiway%2C%20Ontario%20N2A%204A5&amp;t=m&amp;z=15&amp;output=embed&amp;iwloc=near" title="P.O.Box 2503, Kitchener RPO Hiway, Ontario N2A 4A5" aria-label="P.O.Box 2503, Kitchener RPO Hiway, Ontario N2A 4A5"></iframe>
          </div>
        </div>
      </div>

      <div className="space-bottom">
        <div className="container">
          <div className="row flex-row-reverse">
            <div className="col-lg-6 text-lg-end">
              <div className="faq-thumb2 mb-xl-0 mb-50">

                <img src="/assets/img/contact.jpg" alt="Contact-Image" />
              </div>
            </div>
            <div className="col-lg-6">
              <div className="contact-form-wrap p-0">
                <div className="title-area">
                  <span className="sub-title">Get in Touch</span>
                  <h2 className="sec-title">We welcome you to connect with us!</h2>
                </div>
                {/* <form
                  action="mail.php"
                  method="POST"
                  className="appointment-form ajax-contact"
                > */}
                {/* Alert message */}
                {alert.show && (
                  <div className={`alert alert-${alert.type} alert-dismissible fade show`} role="alert">
                    {alert.message}
                    <button type="button" className="btn-close" onClick={() => setAlert({ ...alert, show: false })}></button>
                  </div>
                )}
                <form onSubmit={handleSubmit}>
                  <div className="row">
                    <div className="col-md-6">
                      <FormField
                        type="text"
                        name="name"
                        // label="Full Name"
                        placeholder="Full Name *"
                        value={formData.name}
                        onChange={handleChange}
                        required
                        className={`common-input ${formErrors.name ? "is-invalid" : ""}`}

                      />
                      {formErrors.name && <div className="invalid-feedback d-block">{formErrors.name}</div>}
                    </div>
                    <div className="col-md-6">

                      <FormField
                        type="email"
                        name="email"
                        // label="Email Address"
                        placeholder="Email Address *"
                        value={formData.email}
                        onChange={handleChange}
                        required
                        className={`common-input ${formErrors.email ? "is-invalid" : ""}`}

                      />
                      {formErrors.email && <div className="invalid-feedback d-block">{formErrors.email}</div>}

                    </div>
                    <div className="col-md-6">

                      <FormField
                        type="tel"
                        name="phone"
                        // label="Phone Number"
                        placeholder="Phone Number *"
                        value={formData.phone}
                        onChange={handleChange}
                        required
                        className={`common-input ${formErrors.phone ? "is-invalid" : ""}`}

                      />
                      {formErrors.phone && <div className="invalid-feedback d-block">{formErrors.phone}</div>}
                    </div>
                    <div className="col-md-6">

                      <FormField
                        type="text"
                        name="subject"
                        // label="Email Address"
                        placeholder="Subject"
                        value={formData.subject}
                        onChange={handleChange}
                        required
                        className={`common-input ${formErrors.subject ? "is-invalid" : ""}`}

                      />
                      {formErrors.subject && <div className="invalid-feedback d-block">{formErrors.subject}</div>}
                    </div>
                  </div>
                  <div className="col-12">
                    <FormField
                      type="textarea"
                      name="message"
                      // label="Message"
                      placeholder="Write your message here..."
                      value={formData.message}
                      onChange={handleChange}
                      required
                      className={`common-input h-110 ${formErrors.message ? "is-invalid" : ""}`}

                    />
                    {formErrors.message && <div className="invalid-feedback d-block">{formErrors.message}</div>}
                  </div>
                  <div className="col-12 my-3">
                    <ReCAPTCHA
                      sitekey="6Lf-fpwrAAAAAJAqCwunwiMUFW2PjX4pJlL25xsB"
                      onChange={handleCaptchaChange}
                    />
                    {formErrors.captcha && (
                      <div className="invalid-feedback d-block">{formErrors.captcha}</div>
                    )}
                  </div>
                  <div className="form-btn col-12">
                    <button className="btn style2">
                      Submit <i className="fas fa-arrow-right ms-2" />
                    </button>
                  </div>

                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ContactSection;
