"use client";
import { useState, useEffect } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";
import { BaseUrl } from "@/utility/BaseUrl.utils";

const ContactForm = () => {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone_number: "",
    subject: "",
    message: "",
  });

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

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

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

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

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

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

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

    const emailData = {
      ...formData,
      to: "info@shivasakthi.ca",
      senderName: "Shivasakthi Restaurant",
      recaptchaToken: captchaToken,
    };

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

      setAlert({
        show: true,
        message: res?.data?.message || "Message sent successfully!",
        type: "success",
      });

      setFormData({
        name: "",
        email: "",
        phone_number: "",
        subject: "",
        message: "",
      });
      setCaptchaToken(null);
    } catch (error) {
      setAlert({
        show: true,
        message: "Failed to send message. Please try again later.",
        type: "danger",
      });
    }
  };

  return (
    <div className="contact-page-form">
      <h3>Send Us Message</h3>
      <p>Have a question or need assistance? Fill out the form below and our team will get back to you as soon as possible.
 *</p>
      <form id="contactForm" className="contactForm" name="contactForm" onSubmit={handleSubmit}>
        <div className="row mt-30 gap-20">
          <div className="col-sm-6">
            <div className="form-group">
              <input
                type="text"
                id="name"
                name="name"
                className="form-control"
                placeholder="Full Name"
                required
                data-error="Please enter your Name"
                value={formData.name}
                onChange={handleChange}
              />
              <div className="help-block with-errors" />
            </div>
          </div>
          <div className="col-sm-6">
            <div className="form-group">
              <input
                type="email"
                id="email"
                name="email"
                className="form-control"
                placeholder="Email Address"
                required
                data-error="Please enter your Email"
                value={formData.email}
                onChange={handleChange}
              />
              <div className="help-block with-errors" />
            </div>
          </div>
          <div className="col-sm-6">
            <div className="form-group">
              <input
                type="text"
                id="phone_number"
                name="phone_number"
                className="form-control"
                placeholder="Phone"
                required
                data-error="Please enter your Phone No"
                value={formData.phone_number}
                onChange={handleChange}
              />
              <div className="help-block with-errors" />
            </div>
          </div>
          <div className="col-sm-6">
            <div className="form-group">
              <input
                type="text"
                id="subject"
                name="subject"
                className="form-control"
                placeholder="Subject"
                required
                data-error="Please enter your Subject"
                value={formData.subject}
                onChange={handleChange}
              />
              <div className="help-block with-errors" />
            </div>
          </div>
          <div className="col-sm-12">
            <div className="form-group">
              <textarea
                name="message"
                id="message"
                className="form-control"
                rows={4}
                placeholder="Write Message"
                required
                data-error="Please enter your Message"
                value={formData.message}
                onChange={handleChange}
              />
              <div className="help-block with-errors" />
            </div>
          </div>
          <div className="col-sm-12 mt-3 mb-3">
            <ReCAPTCHA
              sitekey="6LcGsNkrAAAAAKtqLyzbOb9emB3JSHUFSXGiDiO1"
              onChange={handleCaptchaChange}
            />
          </div>
          <div className="col-sm-12">
            <div className="form-group mb-0">
              <button type="submit" className="theme-btn">
                Send Message Us <i className="far fa-arrow-alt-right" />
              </button>
              <div id="msgSubmit" className="hidden" />
            </div>
          </div>
        </div>
      </form>
      {alert.show && (
        <div className={`alert alert-${alert.type} alert-dismissible fade show`} role="alert">
          {alert.message}
          <button
            type="button"
            className="btn-close"
            onClick={() => setAlert({ ...alert, show: false })}
          ></button>
        </div>
      )}
    </div>
  );
};

export default ContactForm;
