"use client";

import { useState, ChangeEvent, FormEvent } from "react";

interface ContactProps {
  siteSettings: any;
}

interface ContactFormData {
  name: string;
  email: string;
  phone: string;
  subject: string;
  message: string;
}

interface ContactFormErrors {
  name?: string;
  email?: string;
  phone?: string;
  subject?: string;
  message?: string;
}

const initialFormData: ContactFormData = {
  name: "",
  email: "",
  phone: "",
  subject: "",
  message: "",
};

const Contact = ({ siteSettings }: ContactProps) => {
  const [formData, setFormData] = useState<ContactFormData>(initialFormData);
  const [errors, setErrors] = useState<ContactFormErrors>({});
  const [loading, setLoading] = useState(false);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;

    let nextValue = value;
    if (name === "phone") {
      nextValue = value.replace(/\D/g, "").slice(0, 10);
    } else if (name === "name") {
      nextValue = value.replace(/[^A-Za-z\s]/g, "");
    }

    setFormData((prev) => ({ ...prev, [name]: nextValue }));
    setErrors((prev) => ({ ...prev, [name]: undefined }));
  };

  const validate = (): boolean => {
    const nextErrors: ContactFormErrors = {};

    if (!formData.name.trim()) {
      nextErrors.name = "Please enter your name.";
    } else if (!/^[A-Za-z\s]+$/.test(formData.name.trim())) {
      nextErrors.name = "Name can only contain letters and spaces.";
    }

    if (!formData.email.trim()) {
      nextErrors.email = "Please enter your email.";
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      nextErrors.email = "Please enter a valid email address.";
    }

    if (!formData.phone.trim()) {
      nextErrors.phone = "Please enter your phone number.";
    } else if (!/^[0-9]{10}$/.test(formData.phone)) {
      nextErrors.phone = "Phone number must be exactly 10 digits.";
    }

    if (!formData.message.trim()) {
      nextErrors.message = "Please enter a message.";
    }

    setErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setSuccessMsg(null);
    setErrorMsg(null);

    if (!validate()) return;

    setLoading(true);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data?.error || "Failed to send your message.");
      }

      setSuccessMsg("Thank you! Your message has been sent. We'll get back to you soon.");
      setFormData(initialFormData);
    } catch (err: any) {
      setErrorMsg(err?.message || "Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <section className="contactcontainer">
      <div className="container container-xxl">
        <div className="row gx-xl-5">
          <div className="col-xxl-7 col-xl-7 col-lg-6 col-md-6 col-sm-12 col-12">
            <div className="contactrt">
              <div className="section-heading mb-3">
                <h2><span>Contact RKDA</span></h2>
                <p>Due to Covid, we transitioned all classes to online from March 2020. Because of RKDA Strong training techniques evolved over 15 yrs we transitioned very smoothly into virtual classes. Our Studios have been updated with TVs and latest technologies max bandwidth etc. In fact, it was a pleasant surprise for us that we achieved more quality training virtually than in-person for following reasons:</p>
                <ul>
                  <li>RKDA is known for its strong training techniques and virtual training added more to it, for example: pinning individual students could identify any posture defect.</li>
                  <li>RKDA is well known for 100% consistent classes; virtual training added more to it, as there are no snow days off.</li>
                  <li>Virtual training at their home comfort, parents listen to RKDA training hence understand the quantity/quality training.</li>
                  <li>Students today are multitasking with many activities so saving drive time is making them more efficient especially when they find out that there is no difference in training virtual/In-person.</li>
                </ul>
                <p>To educate Parents/Students that it is the training techniques that matter and that there is no difference in training whether it is virtual/In-person we provide 4 free classes, Pl avail them. Free classes are only for Virtual training.</p>
              </div>
            </div>
          </div>
          <div className="col-xxl-5 col-xl-5 col-lg-6 col-md-6 col-sm-12 col-12 mb-3 mb-md-0">
            {/* Contact enquiry form */}
            <div className="contactformouter">
              <div className="section-heading mb-3">
                <h3><span>Send us a message</span></h3>
              </div>
              <form className="loginform" onSubmit={handleSubmit} noValidate>
                <div className="row gx-3">
                  <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                    <div className="form-group mb-3">
                      <div className="input-groups">
                        <i className="bi bi-person"></i>
                        <input
                          type="text"
                          name="name"
                          className={`form-control `}
                          value={formData.name}
                          onChange={handleChange}
                          placeholder="Enter full name"
                        />
                      </div>
                      {errors.name && <div className="invalid-feedback d-block">{errors.name}</div>}
                    </div>
                  </div>

                  <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                    <div className="form-group mb-3">
                      <div className="input-groups">
                        <i className="bi bi-envelope"></i>
                        <input
                          type="email"
                          name="email"
                          className={`form-control `}
                          value={formData.email}
                          onChange={handleChange}
                          placeholder="Enter email"
                        />
                      </div>
                      {errors.email && <div className="invalid-feedback d-block">{errors.email}</div>}
                    </div>
                  </div>

                  <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                    <div className="form-group mb-3">
                      <div className="input-groups">
                        <i className="bi bi-telephone-outbound"></i>
                        <input
                          type="text"
                          name="phone"
                          className={`form-control `}
                          value={formData.phone}
                          onChange={handleChange}
                          placeholder="Enter mobile number"
                          maxLength={10}
                        />
                      </div>
                      {errors.phone && <div className="invalid-feedback d-block">{errors.phone}</div>}
                    </div>
                  </div>

                  <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                    <div className="form-group mb-3">
                      <div className="input-groups">
                        <i className="bi bi-chat-left-dots"></i>
                        <input
                          type="text"
                          name="subject"
                          className={`form-control`}
                          value={formData.subject}
                          onChange={handleChange}
                          placeholder="Enter subject"
                        />
                      </div>
                      {errors.subject && <div className="invalid-feedback d-block">{errors.subject}</div>}
                    </div>
                  </div>

                  <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                    <div className="form-group mb-3">
                      <div className="input-groups align-items-start">
                        <i className="bi bi-chat-left-text"></i>
                        <textarea
                          name="message"
                          rows={4}
                          className={`form-control ${errors.message ? "is-invalid" : formData.message ? "is-valid" : ""}`}
                          value={formData.message}
                          onChange={handleChange}
                          placeholder="Enter your message"
                        />
                      </div>
                      {errors.message && <div className="invalid-feedback d-block">{errors.message}</div>}
                    </div>
                  </div>
                </div>

                {successMsg && <p className="text-success small mb-3">{successMsg}</p>}
                {errorMsg && <p className="text-danger small mb-3">{errorMsg}</p>}

                <button type="submit" disabled={loading} className="theme-btn">
                  {loading ? "Sending..." : "Send Message"}
                </button>
              </form>
            </div>
          </div>
          <div className="col-12">
            <div className="studioinfo">
              <div className="section-heading mb-3">
                <h2 className="mb-2 p-0"><span>In-Person</span></h2>
                <p className="mb-2">Currently we have 2 studios in Michigan, one in Troy and the other in Novi.</p>
                <div className="socialicons d-inline-flex d-none mb-0">
                  <a
                    href={siteSettings?.site_whatsapp_link || "#"}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="socialicon whatsapp"
                  >
                    <i className="icon icon-whatsapp"></i>
                  </a>

                  <a
                    href={siteSettings?.site_facebook_link || "#"}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="socialicon facebook"
                  >
                    <i className="icon icon-facebook"></i>
                  </a>

                  <a
                    href={siteSettings?.site_youtube_link || "#"}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="socialicon youtube"
                  >
                    <i className="bi bi-youtube"></i>
                  </a>

                  <a
                    href={siteSettings?.site_instagram_link || "#"}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="socialicon instagram"
                  >
                    <i className="icon icon-instagram"></i>
                  </a>

                  <a
                    href={siteSettings?.site_twitter_link || "#"}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="socialicon twitter"
                  >
                    <i className="icon icon-twitter"></i>
                  </a>
                </div>
              </div>
              <div className="row">
                <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 mb-3 mb-md-0">
                  <div className="studioinfo-item">
                    <h3>Studio 1</h3>
                    <div className="coininfo">
                      <div className="cticon"><i className="bi bi-geo-alt"></i></div>
                      <div className="cticontent">
                        <h4>Address</h4>
                        <p><a href="https://goo.gl/maps/gU31hBpwuViEuanN9" target="_blank" rel="noopener noreferrer">3224 Alpine Rd, Troy, MI 48084</a></p>
                      </div>
                    </div>

                    <div className="coininfo">
                      <div className="cticon"><i className="bi bi-envelope"></i></div>
                      <div className="cticontent">
                        <h4>Email</h4>
                        <p><a href="mailto:rkda.org@gmail.com">rkda.org@gmail.com</a></p>
                      </div>
                    </div>

                    <div className="coininfo">
                      <div className="cticon"><i className="bi bi-telephone"></i></div>
                      <div className="cticontent">
                        <h4>Phone</h4>
                        <p><a href="tel:2487613901">248-761-3901</a></p>
                      </div>
                    </div>

                    <div className="mapbx">
                      <iframe
                        src="https://www.google.com/maps?q=3224+Alpine+Rd,+Troy,+MI+48084&output=embed"
                        style={{ border: 0 }}
                        allowFullScreen
                        loading="lazy"
                        referrerPolicy="no-referrer-when-downgrade"
                        title="Studio 1 - Troy Location"
                      ></iframe>
                    </div>
                  </div>
                </div>
                <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 mb-3 mb-md-0">
                  <div className="studioinfo-item">
                    <h3>Studio 2</h3>
                    <div className="coininfo">
                      <div className="cticon"><i className="bi bi-geo-alt"></i></div>
                      <div className="cticontent">
                        <h4>Address</h4>
                        <p><a href="https://goo.gl/maps/h2U3Y8DQDey1oojd6" target="_blank" rel="noopener noreferrer">
                          Sri Venkateswara Temple &amp; Cultural Center, 26233 Taft Rd, Novi, MI 48374</a></p>
                      </div>
                    </div>

                    <div className="coininfo">
                      <div className="cticon"><i className="bi bi-envelope"></i></div>
                      <div className="cticontent">
                        <h4>Email</h4>
                        <p><a href="mailto:rkda.org@gmail.com">rkda.org@gmail.com</a></p>
                      </div>
                    </div>

                    <div className="coininfo">
                      <div className="cticon"><i className="bi bi-telephone"></i></div>
                      <div className="cticontent">
                        <h4>Phone</h4>
                        <p><a href="tel:2487613901">248-761-3901</a></p>
                      </div>
                    </div>
                    <div className="mapbx">
                      <iframe
                        src="https://www.google.com/maps?q=Sri+Venkateswara+Temple+%26+Cultural+Center,+26233+Taft+Rd,+Novi,+MI+48374&output=embed"
                        style={{ border: 0 }}
                        allowFullScreen
                        loading="lazy"
                        referrerPolicy="no-referrer-when-downgrade"
                        title="Studio 2 - Novi Location"
                      ></iframe>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default Contact;