"use client";

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

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

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

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

  // Handle captcha
  const handleCaptchaChange = (token) => {
    setCaptchaToken(token);
  };

  // Form submit handler
  const handleSubmit = async (e) => {
    e.preventDefault();

    const errors = {};
    if (!formData.username.trim()) errors.username = "First Name is required.";
    if (!formData.lname.trim()) errors.lname = "Last Name is required.";
    if (!formData.email.trim()) errors.email = "Email is required.";
    if (!formData.phone.trim()) errors.phone = "Phone 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: "bloor@rapharehab.ca",
      senderName: "Rapha Rehab 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: "",
        lname: "",
        email: "",
        phone: "",
        subject: "",
        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.",
      });
    }
  };

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

  return (
    <div>
      {/* Contact Info Section */}
      <section className="contact-info-section pt_90">
        <div className="auto-container">
          <div className="row clearfix">
            <div className="col-lg-4 col-md-6 col-sm-12 info-column">
              <div className="info-block-one">
                <h3>Quick Contact</h3>
                <div className="inner-box">
                  <div className="icon-box"><i className="icon-2"></i></div>
                  <p>
                    <Link href="tel:647-722-3434">+647-722-3434</Link><br />
                    <Link href="tel:416-622-2873">+416-622-2873</Link>
                  </p>
                </div>
              </div>
            </div>
            <div className="col-lg-4 col-md-6 col-sm-12 info-column">
              <div className="info-block-one">
                <h3>Email Address</h3>
                <div className="inner-box">
                  <div className="icon-box"><i className="icon-26"></i></div>
                  <p>
                    <Link href="mailto:bloor@rapharehab.ca">bloor@rapharehab.ca</Link>
                  </p>
                </div>
              </div>
            </div>
            <div className="col-lg-4 col-md-6 col-sm-12 info-column">
              <div className="info-block-one">
                <h3>Mailing Address</h3>
                <div className="inner-box">
                  <div className="icon-box">
                    <img src="/assets/images/icons/icon-2.png" alt="" />
                  </div>
                  <p>6 – 4335 Bloor Street West <br />Etobicoke, M9C5S2</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Contact Form Section */}
      <section className="contact-style-three pt_90 pb_90">
        <div className="auto-container">
          <div className="row clearfix">
            <div className="col-lg-8 col-md-12 col-sm-12 form-column">
              <div className="form-inner mr_40">
                <div className="sec-title mb_50">
                  <h2>How can we help?</h2>
                  <p className="mt-3">
                    Please complete the contact information below and let us know your needs. 
                    Upon receipt of your information one of our team members will reach out.
                  </p>
                </div>

                {alert.show && (
                  <div className={`alert alert-${alert.type}`}>{alert.message}</div>
                )}

                <form onSubmit={handleSubmit} className="default-form">
                  <div className="row clearfix">
                    <div className="col-lg-6 col-md-6 col-sm-12 form-group">
                      <input
                        type="text"
                        name="username"
                        placeholder="First Name"
                        value={formData.username}
                        onChange={handleChange}
                      />
                      {formErrors.username && <small className="text-danger">{formErrors.username}</small>}
                    </div>

                    <div className="col-lg-6 col-md-6 col-sm-12 form-group">
                      <input
                        type="text"
                        name="lname"
                        placeholder="Last Name"
                        value={formData.lname}
                        onChange={handleChange}
                      />
                      {formErrors.lname && <small className="text-danger">{formErrors.lname}</small>}
                    </div>

                    <div className="col-lg-6 col-md-6 col-sm-12 form-group">
                      <input
                        type="email"
                        name="email"
                        placeholder="Your Email"
                        value={formData.email}
                        onChange={handleChange}
                      />
                      {formErrors.email && <small className="text-danger">{formErrors.email}</small>}
                    </div>

                    <div className="col-lg-6 col-md-6 col-sm-12 form-group">
                      <input
                        type="text"
                        name="phone"
                        placeholder="Phone"
                        value={formData.phone}
                        onChange={handleChange}
                      />
                      {formErrors.phone && <small className="text-danger">{formErrors.phone}</small>}
                    </div>

                    <div className="col-lg-12 col-md-12 col-sm-12 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 className="col-lg-12 col-md-12 col-sm-12 form-group">
                      <textarea
                        name="message"
                        placeholder="Message"
                        value={formData.message}
                        onChange={handleChange}
                      ></textarea>
                      {formErrors.message && <small className="text-danger">{formErrors.message}</small>}
                    </div>

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

                    <div className="col-lg-12 col-md-12 col-sm-12 form-group message-btn">
                      <button className="theme-btn btn-one" type="submit" name="submit-form">
                        <span>Send Message</span>
                      </button>
                    </div>
                  </div>
                </form>
              </div>
            </div>

            <div className="col-lg-4 col-md-12 col-sm-12 image-column">
              <figure className="image-box">
                <img src="/assets/images/contact/img.webp" alt="contact rapharehab" />
              </figure>
            </div>
          </div>
        </div>
      </section>

      {/* Google Map */}
      <section className="google-map-section">
        <div className="map-inner">
          <iframe
            src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2886.847666572518!2d-79.57789668450145!3d43.6308386791466!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x882b3811bd400001%3A0x87ffabfe7d6aeeca!2s4335+Bloor+St+W+%236%2C+Etobicoke%2C+ON+M9C+5S2%2C+Canada!5e0!3m2!1sen!2sca!4v1693224000000!5m2!1sen!2sca"
            height={570}
            style={{ border: 0, width: "100%" }}
            allowFullScreen
            loading="lazy"
            referrerPolicy="no-referrer-when-downgrade"
          />
        </div>
      </section>
    </div>
  );
}
