"use client";

import { useState, useEffect } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";
import Link from "next/link";
import { servicesList } from "@/utils/Services.utils";

export default function ContactClient() {

  const [email, setEmail] = useState("");

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

  const [formData, setFormData] = useState({
    username: "",
    email: "",
    phone: "",
    service: "",
    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.phone.trim()) errors.phone = "Phone 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 = {
      name: formData.username,
      phone: formData.phone,
      email: formData.email,
      subject: formData.service,
      message: `Service: ${formData.service}<br /><br />Message: ${formData.message}`,
      to: email,
      senderName: "Rapharehab 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: "", phone: "", service: "", message: "" });
      setCaptchaToken(null);
      setFormErrors({});
    } catch (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 (
    <div>
      <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">
                <h2>Quick Contact</h2>
                <div className="inner-box">
                  <div className="icon-box"><i className="icon-2"></i></div>
                  <p>
                    <Link href="tel:647-722-3434" aria-label="+647-722-3434">+647-722-3434</Link><br />
                    <Link href="tel:416-622-2873" aria-label="+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">
                <h2>Email Address</h2>
                <div className="inner-box">
                  <div className="icon-box"><i className="icon-26"></i></div>
                  <p>
                    {email ? (
                      <a href={`mailto:${email}`} aria-label={email}>{email}</a>
                    ) : (
                      <span>Loading...</span>
                    )}
                  </p>
                </div>
              </div>
            </div>
            <div className="col-lg-4 col-md-6 col-sm-12 info-column">
              <div className="info-block-one">
                <h2>Mailing Address</h2>
                <div className="inner-box">
                  <div className="icon-box">
                    <img src="/assets/images/icons/icon-2.png" alt="Address icon" />
                  </div>
                  <p>5 – 4335 Bloor Street West <br />Etobicoke, M9C 2A5</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </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>Contact Rapharehab – Physiotherapy Clinic in Etobicoke</h2>
                  <p className="mt-3">
                    Looking for trusted physiotherapy in Etobicoke? Rapharehab is here to help.
                  </p>
                  <p>Whether you are experiencing pain, recovering from an accident, preparing for surgery, or seeking rehabilitation support, our experienced team is ready to guide you.
                  </p>
                  <p>We make it easy to connect with our physiotherapy clinic in Etobicoke and schedule your first appointment.
                  </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="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="phone"
                        placeholder="Phone"
                        value={formData.phone}
                        onChange={handleChange}
                      />
                      {formErrors.phone && <small className="text-danger">{formErrors.phone}</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">
                      <select
                        name="service"
                        value={formData.service}
                        onChange={handleChange}
                        className="form-control"
                      >
                        <option value="">Select Service</option>
                        {servicesList.map((service) => (
                          <option key={service.slug} value={service.shortTitle}>
                            {service.shortTitle}
                          </option>
                        ))}
                      </select>
                      {formErrors.service && <small className="text-danger">{formErrors.service}</small>}
                    </div>

                    <div className="col-lg-12 col-md-6 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="6Lckq9MrAAAAABjBD9rQYm19BMGFFWiwb9mPiw2K"
                        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="Physiotherapy at Rapharehab" />
              </figure>
            </div>
          </div>
        </div>
      </section>

      <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>
  );
}