"use client";
import { useState, useEffect } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";

export default function AutoPopup() {

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

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

  const [show, setShow] = useState(false);
  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: "" });

  useEffect(() => {
    const timer = setTimeout(() => setShow(true), 5000);
    return () => clearTimeout(timer);
  }, []);

  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 = "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: email,
      senderName: "Rapharehab Auto Popup",
      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) {
      setAlert({
        show: true,
        type: "danger",
        message: "Failed to send message. Please try again later.",
      });
    }
  };

  if (!show) return null;

  return (
    <>
      <div
        className="position-fixed top-0 start-0 w-100 h-100"
        style={{ background: "rgba(0,0,0,0.7)", zIndex: 9998 }}
        onClick={() => setShow(false)}
      ></div>

      <div
        className="position-fixed top-50 start-50 translate-middle bg-white rounded shadow-lg"
        style={{ width: "90%", maxWidth: "700px", zIndex: 9999, overflowY: "auto", maxHeight: "90vh" }}
      >
        <button
          onClick={() => setShow(false)}
          className="btn-close position-absolute"
          style={{ top: "15px", right: "15px", zIndex: 10000 }}
        ></button>

        <div className="p-4 border-bottom">
          <h3 style={{ color: "#bc0000", marginBottom: "5px" }}>
            Welcome to Rapharehab.
          </h3>
          <p style={{ color: "#555", margin: 0 }}>
            We’re here to help — send us a message below.
          </p>
        </div>
        <section className="contact-style-three p-4">
          <div className="auto-container">
            <div className="form-inner">
              {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 form-group message-btn">
                    <button
                      className="theme-btn w-100"
                      type="submit"
                      name="submit-form"
                      style={{
                        background: "#bc0000",
                        color: "#fff",
                        padding: "12px",
                        fontSize: "16px",
                        fontWeight: "bold",
                        border: "none",
                      }}
                    >
                      SUBMIT NOW
                    </button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </section>
      </div>
    </>
  );
}
