import React, { useEffect, useState } from "react";
import { getContact, postQuary } from "@/services/cmsService";
import { toast } from "react-toastify";
import { sanitizeCmsHtml } from "@/utils/safeHtml";

const ContactLeft = React.memo(({ content }) => {
  return (
    <div
      className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12"
      data-aos="fade-up"
      data-aos-delay="1000"
      data-aos-duration="500"
    >
      <div
        dangerouslySetInnerHTML={{
          __html: sanitizeCmsHtml(content || ""),
        }}
      />
    </div>
  );
});

const formatUSPhone = (value) => {
  const digits = value.replace(/\D/g, "").slice(0, 10);
  if (digits.length <= 3) return digits;
  if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
  return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
};

const Contact = () => {
  const [formData, setFormData] = useState({
    name: "",
    phone: "",
    email: "",
    company: "",
    help_type: "",
    message: "",
  });

  // ✅ NEW: errors state for inline messages
  const [errors, setErrors] = useState({
    name: "",
    phone: "",
    email: "",
    company: "",
    help_type: "",
    message: "",
  });

  const [contact, setContact] = useState();
  const [loading, setLoading] = useState(false);

  // ✅ NEW: validate a single field on change
  const validateField = (name, value) => {
    switch (name) {
      case "name":
        if (!value.trim()) return "Name is required";
        if (/\d/.test(value)) return "Name cannot contain numbers";
        if (!/^[a-zA-Z\s'-]+$/.test(value)) return "Name can only contain letters";
        return "";

      case "email":
        if (!value.trim()) return "Email is required";
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return "Please enter a valid email";
        return "";

      case "company":
        if (!value.trim()) return "Organization is required";
        return "";

      case "phone":
        if (!value) return ""; // optional field
        const digits = value.replace(/\D/g, "");
        if (digits.length > 0 && digits.length < 10) return "Please enter a valid 10-digit US phone number";
        return "";

      case "help_type":
        if (!value) return "Please select how we can help";
        return "";

      case "message":
        if (!value.trim()) return "Message is required";
        if (value.trim().length < 10) return "Message must be at least 10 characters";
        return "";

      default:
        return "";
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    let updatedValue = value;

    // ✅ Block numeric characters for name field entirely
    if (name === "name") {
      updatedValue = value.replace(/[0-9]/g, "");
    }

    // Phone formatting
    if (name === "phone") {
      updatedValue = formatUSPhone(value);
    }

    setFormData((prev) => ({ ...prev, [name]: updatedValue }));

    // ✅ Validate on every keystroke and update error
    const error = validateField(name, updatedValue);
    setErrors((prev) => ({ ...prev, [name]: error }));
  };

  // ✅ Full form validation before submit (also sets all errors at once)
  const validateForm = () => {
    const newErrors = {
      name: validateField("name", formData.name),
      email: validateField("email", formData.email),
      company: validateField("company", formData.company),
      phone: validateField("phone", formData.phone),
      help_type: validateField("help_type", formData.help_type),
      message: validateField("message", formData.message),
    };

    setErrors(newErrors);

    // Return false if any error exists
    return !Object.values(newErrors).some((err) => err !== "");
  };

  const getContactDetails = async () => {
    try {
      const response = await getContact();
      setContact(response.data);
    } catch (error) {
      console.error("Error fetching contact data:", error);
    }
  };

  useEffect(() => {
    getContactDetails();
  }, []);

  const handleSubmit = async () => {
    if (!validateForm()) return;

    try {
      setLoading(true);

      const payload = {
        name: formData.name,
        phone: formData.phone.replace(/\D/g, ""),
        email: formData.email,
        company: formData.company,
        help_type: formData.help_type,
        message: formData.message,
      };

      await postQuary(payload);
      toast.success("Your message has been sent successfully!");

      setFormData({
        name: "",
        phone: "",
        email: "",
        company: "",
        help_type: "",
        message: "",
      });

      // ✅ Clear errors after successful submit
      setErrors({
        name: "",
        phone: "",
        email: "",
        company: "",
        help_type: "",
        message: "",
      });
    } catch (error) {
      toast.error("There was an error sending your message.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <section className="contactcontainer contactinnercontainer">
      <div className="contactinner">
        <div className="container">
          <div className="row gx-lg-5 justify-content-center align-items-center">
            <ContactLeft content={contact?.content} />

            <div
              className="col-xxl-6 col-xl-6 col-lg-7 col-md-6 col-sm-12 col-12 d-flex align-items-center"
              data-aos="zoom-in"
              data-aos-delay="1000"
              data-aos-duration="500"
            >
              <div className="contactform w-100">
                <div className="section-heading flex-fill mb-2">
                  <div className="subheading">Let's Connect.</div>
                  <h2>Contact Us</h2>
                </div>

                <div className="row gx-2 gx-lg-3">
                  {/* Name */}
                  <div className="col-md-6 mb-3">
                    <div className="form-group">
                      <input
                        type="text"
                        className={`form-control ${errors.name ? "is-invalid" : formData.name ? "is-valid" : ""}`}
                        placeholder="Name"
                        name="name"
                        value={formData.name}
                        onChange={handleChange}
                      />
                      {errors.name && (
                        <div className="invalid-feedback d-block">
                          {errors.name}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Email */}
                  <div className="col-md-6 mb-3">
                    <div className="form-group">
                      <input
                        type="email"
                        className={`form-control ${errors.email ? "is-invalid" : formData.email ? "is-valid" : ""}`}
                        placeholder="Email"
                        name="email"
                        value={formData.email}
                        onChange={handleChange}
                      />
                      {errors.email && (
                        <div className="invalid-feedback d-block">
                          {errors.email}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Organization */}
                  <div className="col-md-6 mb-3">
                    <div className="form-group">
                      <input
                        type="text"
                        className={`form-control ${errors.company ? "is-invalid" : formData.company ? "is-valid" : ""}`}
                        placeholder="Organization"
                        name="company"
                        value={formData.company}
                        onChange={handleChange}
                      />
                      {errors.company && (
                        <div className="invalid-feedback d-block">
                          {errors.company}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Phone */}
                  <div className="col-md-6 mb-3">
                    <div className="form-group">
                      <input
                        type="text"
                        className={`form-control ${errors.phone ? "is-invalid" : formData.phone && !errors.phone ? "is-valid" : ""}`}
                        placeholder="Phone (optional)"
                        name="phone"
                        value={formData.phone}
                        onChange={handleChange}
                      />
                      {errors.phone && (
                        <div className="invalid-feedback d-block">
                          {errors.phone}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Dropdown */}
                  <div className="col-12 mb-3">
                    <div className="form-group">
                      <select
                        className={`form-control ${errors.help_type ? "is-invalid" : formData.help_type ? "is-valid" : ""}`}
                        name="help_type"
                        value={formData.help_type}
                        onChange={handleChange}
                      >
                        <option value="">How can we help?</option>
                        <option value="Request Demo">Request Demo</option>
                        <option value="General Inquiry">General Inquiry</option>
                        <option value="Partnership Opportunity">Partnership Opportunity</option>
                        <option value="Other">Other</option>
                      </select>
                      {errors.help_type && (
                        <div className="invalid-feedback d-block">
                          {errors.help_type}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Message */}
                  <div className="col-12 mb-3">
                    <div className="form-group">
                      <textarea
                        className={`form-control ${errors.message ? "is-invalid" : formData.message ? "is-valid" : ""}`}
                        placeholder="Message"
                        rows={4}
                        name="message"
                        value={formData.message}
                        onChange={handleChange}
                      />
                      {errors.message && (
                        <div className="invalid-feedback d-block">
                          {errors.message}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Submit */}
                  <div className="col-12">
                    <button
                      className="theme-btn w-100"
                      type="button"
                      onClick={handleSubmit}
                      disabled={loading}
                    >
                      {loading ? "Submitting..." : "Submit"}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

export default Contact;