"use client";

import { useState, useEffect, useRef } from "react";
import ReCAPTCHA from "react-google-recaptcha";

const initialFormData = {
  name: "",
  email: "",
  subject: "",
  message: "",
};

const initialAlert = {
  show: false,
  type: "",
  message: "",
};

export default function ContactForm() {
  const [formData, setFormData] = useState(initialFormData);
  const [alert, setAlert] = useState(initialAlert);
  const [captchaToken, setCaptchaToken] = useState(null);
  const recaptchaRef = useRef(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();

    if (!formData.name || !formData.email || !formData.subject || !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: "mydosaplacewaterloo@gmail.com",
      senderName: "My Dosa Place Contact Form",
      message: `
        <b>Name:</b> ${formData.name}<br/>
        <b>Email:</b> ${formData.email}<br/>
        <b>Subject:</b> ${formData.subject}<br/>
        <b>Message:</b><br/>${formData.message}
      `,
    };

    try {
      const response = await fetch("https://mailserver.metatronnest.com/send", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(emailData),
      });

      if (!response.ok) {
        throw new Error("Failed to send message");
      }

      setAlert({ show: true, type: "success", message: "Your message has been sent successfully!" });
      setFormData(initialFormData);
      setCaptchaToken(null);
      if (recaptchaRef.current) {
        recaptchaRef.current.reset();
      }
    } catch (error) {
      setAlert({ show: true, type: "danger", message: "Failed to send your message. Try again later." });
    }
  };

  useEffect(() => {
    if (!alert.show) return;

    const timer = window.setTimeout(() => {
      setAlert(initialAlert);
    }, 5000);

    return () => window.clearTimeout(timer);
  }, [alert.show]);

  return (
    <form className="contact-form" onSubmit={handleSubmit}>
      {alert.show && (
        <div className={`alert ${alert.type === "success" ? "alert-success" : "alert-danger"}`}>
          {alert.message}
        </div>
      )}

      <div className="form-group">
        <label htmlFor="name">Name</label>
        <input
          type="text"
          id="name"
          name="name"
          placeholder="Your Name"
          value={formData.name}
          onChange={handleChange}
          required
        />
      </div>

      <div className="form-group">
        <label htmlFor="email">Email</label>
        <input
          type="email"
          id="email"
          name="email"
          placeholder="message@domain.com"
          value={formData.email}
          onChange={handleChange}
          required
        />
      </div>

      <div className="form-group">
        <label htmlFor="subject">Subject</label>
        <input
          type="text"
          id="subject"
          name="subject"
          placeholder="Title"
          value={formData.subject}
          onChange={handleChange}
          required
        />
      </div>

      <div className="form-group">
        <label htmlFor="message">Message</label>
        <textarea
          id="message"
          name="message"
          rows="4"
          placeholder="Type here..."
          value={formData.message}
          onChange={handleChange}
          required
        ></textarea>
      </div>

      <div className="captcha-wrapper">
        <ReCAPTCHA
          ref={recaptchaRef}
          sitekey="6LeaPggsAAAAAM4DHBSX0y3IC6lu9SrJIhoQKZKo"
          onChange={handleCaptchaChange}
        />
      </div>

      <button type="submit" className="submit-btn">
        Send Now
      </button>
    </form>
  );
}
