"use client";
import React, { useRef, useState } from "react";
import { toast } from "react-toastify";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";
import "react-toastify/dist/ReactToastify.css";
import AnimatedText from "../common/AnimatedText";

export default function ContactForm() {
  const form = useRef();

  const [formData, setFormData] = useState({
    firstName: "",
    email: "",
    number: "",
    message: "",
    product: "",
  });

  const [formErrors, setFormErrors] = useState({});
  const [captchaToken, setCaptchaToken] = useState(null);

  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.firstName.trim()) errors.firstName = "First name is required.";
    if (!formData.email.trim()) errors.email = "Email is required.";
    if (!formData.number.trim()) errors.number = "Phone number is required.";
    if (!formData.product.trim()) errors.product = "Please select a product.";
    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 = {
      name: formData.firstName,
      email: formData.email,
      phone: formData.number,
      service: formData.product,
      message: `Message: ${formData.message}`,
      to: "lead@metatroncube.in",
      senderName: "Metatroncube Landing",
      recaptchaToken: captchaToken,
    };

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

      toast.success(res?.data?.message || "Message sent successfully!", {
        position: "bottom-right",
        autoClose: 5000,
      });

      setFormData({
        firstName: "",
        email: "",
        number: "",
        message: "",
        product: "",
      });
      setCaptchaToken(null);
      setFormErrors({});
      form.current.reset();
    } catch (err) {
      toast.error("Failed to send message. Please try again later.", {
        position: "bottom-right",
        autoClose: 5000,
      });
    }
  };

  return (
    <section className="contact-section-22">
      <div className="container">
        <div className="contact-form-items">
          <div className="title text-center">
            <h2 className="splt-txt wow">
              <AnimatedText text="Get In Touch" />
            </h2>
          </div>
          <form ref={form} onSubmit={handleSubmit}>
            <div className="row g-4">
              <div className="col-lg-6 wow fadeInUp" data-wow-delay=".2s">
                <div className="form-clt">
                  <input
                    type="text"
                    name="firstName"
                    placeholder="Your Name"
                    value={formData.firstName}
                    onChange={handleChange}
                    required
                  />
                  <div className="icon">
                    <i className="fa-regular fa-user" />
                  </div>
                  {formErrors.firstName && (
                    <div className="text-danger mt-1">{formErrors.firstName}</div>
                  )}
                </div>
              </div>

              <div className="col-lg-6 wow fadeInUp" data-wow-delay=".4s">
                <div className="form-clt">
                  <input
                    type="email"
                    name="email"
                    placeholder="Email Address"
                    value={formData.email}
                    onChange={handleChange}
                    required
                  />
                  <div className="icon">
                    <i className="fa-regular fa-envelope" />
                  </div>
                  {formErrors.email && (
                    <div className="text-danger mt-1">{formErrors.email}</div>
                  )}
                </div>
              </div>

              <div className="col-lg-6 wow fadeInUp" data-wow-delay=".2s">
                <div className="form-clt">
                  <input
                    type="text"
                    name="number"
                    placeholder="Phone Number"
                    value={formData.number}
                    onChange={handleChange}
                    required
                  />
                  <div className="icon">
                    <i className="fa-regular fa-phone" />
                  </div>
                  {formErrors.number && (
                    <div className="text-danger mt-1">{formErrors.number}</div>
                  )}
                </div>
              </div>

              <div className="col-lg-6 wow fadeInUp" data-wow-delay=".4s">
                <div className="form-clt">
                  <select
                    name="product"
                    value={formData.product}
                    onChange={handleChange}
                    required
                    className="form-select"
                  >
                    <option value="">-- Select Product --</option>
                    <option value="Coconut Deshelling Machine">
                      Coconut Deshelling Machine
                    </option>
                    <option value="Coconut Dryer (Hot Air / Tray Type)">
                      Coconut Dryer (Hot Air / Tray Type)
                    </option>
                    <option value="Coconut Pulverizer & Grinder">
                      Coconut Pulverizer & Grinder
                    </option>
                    <option value="Coconut Milk Extractor">
                      Coconut Milk Extractor
                    </option>
                    <option value="Virgin Coconut Oil (VCO) Processing Equipment">
                      Virgin Coconut Oil (VCO) Processing Equipment
                    </option>
                    <option value="Coconut Water Processing Unit">
                      Coconut Water Processing Unit
                    </option>
                  </select>
                  <div className="icon">
                    <i className="fa-solid fa-box" />
                  </div>
                  {formErrors.product && (
                    <div className="text-danger mt-1">{formErrors.product}</div>
                  )}
                </div>
              </div>

              <div className="col-lg-12 wow fadeInUp" data-wow-delay=".2s">
                <div className="form-clt">
                  <textarea
                    name="message"
                    placeholder="What’s on your mind"
                    value={formData.message}
                    onChange={handleChange}
                    required
                  />
                  <div className="icon">
                    <i className="fa-sharp fa-light fa-pencil" />
                  </div>
                  {formErrors.message && (
                    <div className="text-danger mt-1">{formErrors.message}</div>
                  )}
                </div>
              </div>

              <div className="col-lg-12 wow fadeInUp" data-wow-delay=".3s">
                <ReCAPTCHA
                  sitekey="6LcmnZYrAAAAAL62hHdDnlbvznuOpcHfZIc3DN5b"
                  onChange={handleCaptchaChange}
                />
                {formErrors.captcha && (
                  <div className="text-danger mt-2">{formErrors.captcha}</div>
                )}
              </div>

              <div className="col-lg-12 wow fadeInUp" data-wow-delay=".4s">
                <button type="submit" className="theme-btn w-100">
                  SEND MESSAGE NOW
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}
