import React, { useState } from "react";
import "../styles/ContactUs.css";
import contactHeroImg from "../assets/contact-hero.jpg";
import centerImg from "../assets/contact-center.jpg";

const ContactUs = () => {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    contact: "",
    message: "",
  });

  const [formErrors, setFormErrors] = useState({
    name: "",
    email: "",
    contact: "",
    message: "",
  });

  const [loading, setLoading] = useState(false);
  const [notice, setNotice] = useState(null);

  const API_BASE = (process.env.REACT_APP_API_BASE_URL || "").replace(/\/+$/, "");

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    
    // Clear error when user starts typing
    if (formErrors[name]) {
      setFormErrors((prev) => ({ ...prev, [name]: "" }));
    }
  };

  const validateForm = () => {
    const errors = {};
    let isValid = true;

    // Name validation
    if (!formData.name.trim()) {
      errors.name = "Name is required";
      isValid = false;
    } else if (formData.name.trim().length < 2) {
      errors.name = "Name must be at least 2 characters";
      isValid = false;
    }

    // Email validation
    if (!formData.email.trim()) {
      errors.email = "Email is required";
      isValid = false;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      errors.email = "Please enter a valid email address";
      isValid = false;
    }

    // Contact validation
    const digits = (formData.contact || "").replace(/\D/g, "");
    if (!formData.contact.trim()) {
      errors.contact = "Contact number is required";
      isValid = false;
    } else if (digits.length < 7) {
      errors.contact = "Please enter a valid contact number (at least 7 digits)";
      isValid = false;
    }

    // Message validation
    if (!formData.message.trim()) {
      errors.message = "Message is required";
      isValid = false;
    } else if (formData.message.trim().length < 10) {
      errors.message = "Message must be at least 10 characters";
      isValid = false;
    }

    setFormErrors(errors);
    return isValid;
  };

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

    if (!validateForm()) {
      setNotice({ type: "error", text: "Please correct the errors in the form." });
      return;
    }

    setLoading(true);
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 20000);

    try {
      const res = await fetch(`${API_BASE}/contact`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
        signal: controller.signal,
      });

      const data = await res.json().catch(() => ({}));

      if (res.ok) {
        setNotice({ type: "success", text: data.message || "Message sent successfully! We'll get back to you soon." });
        setFormData({ name: "", email: "", contact: "", message: "" });
      } else {
        setNotice({
          type: "error",
          text: data?.error || `Something went wrong (HTTP ${res.status}). Please try again.`,
        });
      }
    } catch (err) {
      if (err.name === "AbortError") {
        setNotice({ type: "error", text: "Request timed out. Please try again." });
      } else {
        setNotice({ type: "error", text: "Network error. Please check your connection and try again." });
      }
    } finally {
      clearTimeout(timeoutId);
      setLoading(false);
    }
  };

  return (
    <div className="contact-page">
      <div
        className="contact-hero"
        style={{ backgroundImage: `url(${contactHeroImg})` }}
        role="img"
        aria-label="Contact page hero"
      >
        <div className="contact-overlay">
          <h1>CONTACT US</h1>
        </div>
      </div>

      <div className="contact-heading">
        <h2>LET'S RISE TOGETHER</h2>
        <p className="subheading">We have the highest of ambitions and are here to support you rise higher!</p>
        <p className="description">
          Whether you are a client looking for a solution or an associate looking for a partner, feel free to connect
          with us.
        </p>
      </div>

      <div className="contact-content">
        <div className="contact-info">
          <h3>MEET US</h3>
          <hr />
          <div className="office-block">
            <h4>KOLHAPUR OFFICE</h4>
            <p>
              Laxmi Civil Engineering Services Pvt. Ltd.<br />
              1148, E. Sykes Extension, Kolhapur 416 001, Maharashtra, India.
            </p>
            <p>Phone No: 0231-2683900</p>
          </div>  
        </div>

        <div className="contact-center-image">
          <img src={centerImg} alt="Office" />
        </div>

        <div className="contact-form">
          <h3>SHARE YOUR THOUGHTS AND WE'LL CONTACT YOU!</h3>

          {notice && (
            <div className={`notice ${notice.type === "success" ? "notice-success" : "notice-error"}`} role="alert">
              {notice.text}
            </div>
          )}

          <form onSubmit={handleSubmit} noValidate>
            <div className="input-group">
              <input
                type="text"
                name="name"
                placeholder="Name*"
                value={formData.name}
                onChange={handleChange}
                required
                autoComplete="name"
                disabled={loading}
                className={formErrors.name ? "error" : ""}
              />
              {formErrors.name && <span className="error-text">{formErrors.name}</span>}
            </div>
            
            <div className="input-group">
              <input
                type="email"
                name="email"
                placeholder="Email*"
                value={formData.email}
                onChange={handleChange}
                required
                autoComplete="email"
                disabled={loading}
                className={formErrors.email ? "error" : ""}
              />
              {formErrors.email && <span className="error-text">{formErrors.email}</span>}
            </div>
            
            <div className="input-group">
              <input
                type="text"
                name="contact"
                placeholder="Contact*"
                value={formData.contact}
                onChange={handleChange}
                required
                autoComplete="tel"
                inputMode="tel"
                disabled={loading}
                className={formErrors.contact ? "error" : ""}
              />
              {formErrors.contact && <span className="error-text">{formErrors.contact}</span>}
            </div>
            
            <div className="input-group">
              <textarea
                name="message"
                placeholder="Message*"
                value={formData.message}
                onChange={handleChange}
                required
                rows={5}
                disabled={loading}
                className={formErrors.message ? "error" : ""}
              />
              {formErrors.message && <span className="error-text">{formErrors.message}</span>}
            </div>
            
            <button type="submit" disabled={loading}>
              {loading ? "SENDING..." : "SUBMIT"}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ContactUs;