"use client";

import { useState, useEffect } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";
import Layout from "@/components/layout/Layout";
import Link from "next/link";

export default function Contact() {
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    subject: "",
    message: "",
  });

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

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

  const handleCaptchaChange = (token) => {

    setCaptchaToken(token);
  };

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

    const errors = {};
    if (!formData.username.trim()) errors.username = "Name is required.";
    if (!formData.email.trim()) errors.email = "Email 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) {
      return;
    }

    const emailData = {
      ...formData,
      message: `Subject: ${formData.subject}<br /><br />Message: ${formData.message}`,
      to: "info@zipvan.ca",
      senderName: "ZipVan Contact Page",
      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 || "Message sent successfully!",
      });

      setFormData({ username: "", email: "", subject: "", message: "" });
      setCaptchaToken(null);
      setFormErrors({});
    } catch (error) {
      setAlert({
        show: true,
        type: "danger",
        message: "Failed to send message. Please try again later.",
      });
    }
  };

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

  return (
    <>
      <Layout breadcrumbTitle="Contact" background="/assets/images/contact/contact-banner.webp" footerStyle={2}>
        <section className="contact-section">
          <div className="pd_top_90" />
          <div className="container">
            {/* Use g-4 to add spacing between all cards responsively */}
            <div className="row align-items-stretch g-4">
              <div className="col-lg-4 col-md-6 col-sm-12">
                <div className="contact_box_content h-100 d-flex flex-column justify-content-center">
                  <div className="icon trans">
                    <img src="/assets/images/cont-1.png" alt="img" className="img-fluid" />
                  </div>
                  <div className="contact-infor">
                    <h6 className="title_no_a_24">Location</h6>
                    <span>55 Main Street, 2nd Block melbourne, Australia</span>
                  </div>
                </div>
              </div>

              <div className="col-lg-4 col-md-6 col-sm-12">
                <div className="contact_box_content h-100 d-flex flex-column justify-content-center">
                  <div className="icon trans">
                    <img src="/assets/images/cont-2.png" alt="img" className="img-fluid" />
                  </div>
                  <div className="contact-infor">
                    <h6 className="title_no_a_24">Email</h6>
                    <Link href="mailto:info@zipvan.ca">info@zipvan.ca</Link>
                  </div>
                </div>
              </div>

              <div className="col-lg-4 col-md-6 col-sm-12">
                <div className="contact_box_content h-100 d-flex flex-column justify-content-center">
                  <div className="icon trans">
                    <img src="/assets/images/cont-3.png" alt="img" className="img-fluid" />
                  </div>
                  <div className="contact-infor">
                    <h6 className="title_no_a_24">Call Us</h6>
                    <Link href="tel:(647) 360-2075">(647) 360-2075</Link>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="pd_bottom_90" />
        </section>

        {/* form */}
        <section className="form-section bg_light_1 position-relative">
          <div className="pd_top_90" />
          <div className="container">
            <div className="row">
              <div className="col-lg-4 col-md-12">
                <div className="section_title type_one">
                  <h4 className="sm_title"> Get In Touch</h4>
                  <div className="title_whole">
                    <h2 className="title"> Contact Zip Van We’re Here to Help</h2>
                  </div>
                  <p>
                    Get in touch with us for bookings, pricing, or any questions. We’re here to help you move with ease.
                  </p>
                </div>
                <div className="pd_bottom_40" />
                <div className="social-icons">
                  <ul>
                    <li>
                      <Link href="#" className="m_icon">
                        <i className="fab fa-instagram" />
                      </Link>
                    </li>
                  </ul>
                </div>
                <div className="pd_bottom_20" />
              </div>

              <div className="col-lg-8 col-md-12">
                <section className="contact_form_box_all">
                  <div className="contact_form_shortcode">
                    {alert.show && (
                      <div className={`alert alert-${alert.type}`}>{alert.message}</div>
                    )}

                    <form onSubmit={handleSubmit} role="form">
                      <div className="controls">
                        <div className="row">
                          <div className="col-md-6 col-sm-12">
                            <div className="form-group">
                              <input
                                type="text"
                                name="username"
                                placeholder="Your Name *"
                                value={formData.username}
                                onChange={handleChange}
                              />
                              {formErrors.username && (
                                <small className="text-danger">{formErrors.username}</small>
                              )}
                            </div>
                          </div>
                          <div className="col-md-6 col-sm-12">
                            <div className="form-group">
                              <input
                                type="email"
                                name="email"
                                placeholder="Email *"
                                value={formData.email}
                                onChange={handleChange}
                              />
                              {formErrors.email && (
                                <small className="text-danger">{formErrors.email}</small>
                              )}
                            </div>
                          </div>
                          <div className="col-sm-12">
                            <div className="form-group">
                              <input
                                type="text"
                                name="subject"
                                placeholder="Subject *"
                                value={formData.subject}
                                onChange={handleChange}
                              />
                              {formErrors.subject && (
                                <small className="text-danger">{formErrors.subject}</small>
                              )}
                            </div>
                          </div>
                          <div className="col-sm-12">
                            <div className="form-group">
                              <textarea
                                name="message"
                                placeholder="Additional Information..."
                                rows={3}
                                value={formData.message}
                                onChange={handleChange}
                              />
                              {formErrors.message && (
                                <small className="text-danger">{formErrors.message}</small>
                              )}
                            </div>
                          </div>

                          <div className="col-sm-12 mb-3">
                            <ReCAPTCHA
                              sitekey="6LekfpwrAAAAAOTwuP1d2gg-Fv9UEsAjE2gjOQJl"
                              onChange={handleCaptchaChange}
                            />
                            {formErrors.captcha && (
                              <small className="text-danger">{formErrors.captcha}</small>
                            )}
                          </div>

                          <div className="col-sm-12">
                            <div className="form-group mg_top apbtn">
                              <button className="theme_btn" type="submit">
                                Send Message
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </form>
                  </div>
                </section>
              </div>
            </div>
          </div>
          <div className="ab_img_left_bottom z_0 mr_top_minus_150">
            <img src="/assets/images/bg-1.png" className="img-fluid" alt="img" />
          </div>
          <div className="pd_bottom_90" />
        </section>

        <section className="contact-map-section">
          <div className="container-no">
            <div className="row">
              <div className="col-lg-12">
                <section className="map-section">
                  <div className="map-outer">
                    <iframe
                      src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2643.6895046810805!2d-122.52642526124438!3d38.00014098339506!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8085976736097a2f%3A0xbe014d20e6e22654!2sSan%20Rafael%2C%20California!5e0!3m2!1sen!2s!4v1678975266976!5m2!1sen!2s"
                      height={570}
                      style={{ border: 0, width: "100%" }}
                      allowFullScreen
                      loading="lazy"
                      referrerPolicy="no-referrer-when-downgrade"
                    />
                  </div>
                </section>
              </div>
            </div>
          </div>
        </section>
      </Layout>
    </>
  );
}
