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

export default function ContactForm() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    message: "",
  });

  const [alert, setAlert] = useState({
    show: false,
    type: "",
    message: "",
  });

  const [captchaToken, setCaptchaToken] = useState(null);

  const handleCaptchaChange = (token) => {
    setCaptchaToken(token);
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

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

    if (!formData.name || !formData.email || !formData.phone || !formData.message) {
      setAlert({ show: true, type: "danger", message: "Please fill in all fields." });
      return;
    }

    if (!captchaToken) {
      setAlert({ show: true, type: "danger", message: "Please verify the CAPTCHA." });
      return;
    }

    const emailData = {
      ...formData,
      recaptchaToken: captchaToken,
      to: "sixty5street@gmail.com",
      senderName: "Sixty5Street Contact Form",
      message: `
        <b>Name:</b> ${formData.name}<br/>
        <b>Email:</b> ${formData.email}<br/>
        <b>Phone:</b> ${formData.phone}<br/><br/>
        <b>Message:</b><br/>${formData.message}
      `,
    };

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

      setAlert({ show: true, type: "success", message: "Your message has been sent successfully!" });
      setFormData({ name: "", email: "", phone: "", message: "" });
      setCaptchaToken(null);
    } catch {
      setAlert({ show: true, type: "danger", message: "Failed to send your message. Try again later." });
    }
  };

  useEffect(() => {
    if (alert.show) {
      const timer = setTimeout(() => setAlert({ show: false, type: "", message: "" }), 5000);
      return () => clearTimeout(timer);
    }
  }, [alert.show]);

  return (
    <div className="contact-form">
      {alert.show && (
        <div className={`alert ${alert.type === "success" ? "text-green-600" : "text-red-600"}`}>
          {alert.message}
        </div>
      )}

      <form onSubmit={handleSubmit}>
        <div className="row clearfix">
          <div className="col-lg-6 col-md-12 col-sm-12 form-group">
            <input
              type="text"
              name="name"
              placeholder="Your Name"
              value={formData.name}
              onChange={handleChange}
              required
            />
          </div>

          <div className="col-lg-6 col-md-12 col-sm-12 form-group">
            <input
              type="text"
              name="phone"
              placeholder="Your Phone Number"
              value={formData.phone}
              onChange={handleChange}
              required
            />
          </div>

          <div className="col-lg-12 col-md-12 col-sm-12 form-group">
            <input
              type="email"
              name="email"
              placeholder="Your Email"
              value={formData.email}
              onChange={handleChange}
              required
            />
          </div>

          <div className="col-lg-12 col-md-12 col-sm-12 form-group">
            <textarea
              name="message"
              placeholder="Your Message"
              value={formData.message}
              onChange={handleChange}
              required
            ></textarea>
          </div>

          <div className="col-lg-12 col-md-12 col-sm-12 form-group">
            <ReCAPTCHA
              sitekey="6LeaPggsAAAAAM4DHBSX0y3IC6lu9SrJIhoQKZKo"
              onChange={handleCaptchaChange}
            />
          </div>

          <div className="col-lg-12 col-md-12 col-sm-12 form-group">
            <button type="submit" className="theme-btn btn-style-four">
              <span className="icon flaticon-arrow-pointing-to-right"></span> Send
            </button>
          </div>
        </div>
      </form>
    </div>
  );
}
