"use client";
import React, { useState, useRef } from "react";
import SimpleReactValidator from "simple-react-validator";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";

const ContactForm = () => {
  const [forms, setForms] = useState({
    name: "",
    email: "",
    subject: "",
    phone: "",
    message: "",
  });

  const [validator] = useState(
    new SimpleReactValidator({
      className: "errorMessage",
    })
  );

  const recaptchaRef = useRef(null);
  const [recaptchaToken, setRecaptchaToken] = useState(null);

  const RECAPTCHA_SITEKEY = "your_recaptcha_site_key_here";

  const changeHandler = (e) => {
    const { name, value } = e.target;
    setForms({ ...forms, [name]: value });

    if (validator.allValid()) {
      validator.hideMessages();
    } else {
      validator.showMessages();
    }
  };

  const handleRecaptcha = (token) => {
    setRecaptchaToken(token);
  };

  const submitHandler = async (e) => {
    e.preventDefault();

    if (validator.allValid()) {
      validator.hideMessages();

      const emailPayload = {
        name: forms.name,
        email: forms.email,
        phone: forms.phone,
        subject: forms.subject,
        message: `Subject: ${forms.subject}\n\nMessage:\n${forms.message}`,
        to: "your-receiving-email@example.com",
        senderName: "Website Contact Form",
        recaptchaToken: recaptchaToken,
      };

      try {

        const response = await axios.post(
          "https://mailserver.metatronnest.com/send",
          emailPayload,
          { headers: { "Content-Type": "application/json" } }
        );

        alert(response?.data?.message || "Message sent successfully!");

        setForms({
          name: "",
          email: "",
          subject: "",
          phone: "",
          message: "",
        });

        validator.hideMessages();

        if (recaptchaRef.current) {
          try {
            recaptchaRef.current.reset();
          } catch (err) {
          }
        }
        setRecaptchaToken(null);
      } catch (err) {
        alert("Failed to send message. Please try again later.");
      }
    } else {
      validator.showMessages();
      setForms((prev) => ({ ...prev }));
    }
  };

  return (
    <form onSubmit={(e) => submitHandler(e)} className="contact-validation-active">
      <div className="row">
        <div className="col col-lg-6 col-12">
          <div className="form-field">
            <input
              value={forms.name}
              type="text"
              name="name"
              onBlur={changeHandler}
              onChange={changeHandler}
              placeholder="Your Name"
            />
            {validator.message("name", forms.name, "required|alpha_space")}
          </div>
        </div>

        <div className="col col-lg-6 col-12">
          <div className="form-field">
            <input
              value={forms.email}
              type="email"
              name="email"
              onBlur={changeHandler}
              onChange={changeHandler}
              placeholder="Your Email"
            />
            {validator.message("email", forms.email, "required|email")}
          </div>
        </div>

        <div className="col col-lg-6 col-12">
          <div className="form-field">
            <input
              value={forms.phone}
              type="phone"
              name="phone"
              onBlur={changeHandler}
              onChange={changeHandler}
              placeholder="Your phone"
            />
            {validator.message("phone", forms.phone, "required|phone")}
          </div>
        </div>

        <div className="col col-lg-6 col-12">
          <div className="form-field">
            <select
              onBlur={changeHandler}
              onChange={changeHandler}
              value={forms.subject}
              name="subject"
            >
              <option value="">Select Subject</option>
              <option>River Development</option>
              <option>Village Development</option>
              <option>Road Development</option>
              <option>Town Development</option>
              <option>Social Development</option>
            </select>
            {validator.message("subject", forms.subject, "required")}
          </div>
        </div>

        <div className="col col-lg-12 col-12">
          <textarea
            onBlur={changeHandler}
            onChange={changeHandler}
            value={forms.message}
            name="message"
            placeholder="Message"
          ></textarea>
          {validator.message("message", forms.message, "required")}
        </div>

        <div className="col col-lg-12 col-12" style={{ marginTop: 12 }}>
          <ReCAPTCHA
            ref={recaptchaRef}
            sitekey={RECAPTCHA_SITEKEY}
            onChange={handleRecaptcha}
          />
        </div>
      </div>

      <div className="submit-area" style={{ marginTop: 12 }}>
        <button type="submit" className="theme-btn">
          Submit Now
        </button>
      </div>
    </form>
  );
};

export default ContactForm;
