import React, { useEffect, useState } from "react";
import { sendEmail } from "@/app/utils/send-email";

export type ContactFormData = {
  name: string;
  email: string;
  message: string;
};

export default function Contact() {
  const [isVisible, setIsVisible] = useState(false);
  const [banner, setBanner] = useState<{
    show: boolean;
    message: string;
    type: "success" | "error";
  }>({
    show: false,
    message: "",
    type: "success",
  });
  // Record the time when the form is rendered
  const [formLoadedTimestamp, setFormLoadedTimestamp] = useState<number>(Date.now());

  useEffect(() => {
    setFormLoadedTimestamp(Date.now());
    setTimeout(() => {
      setIsVisible(true);
    }, 350);
  }, []);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();

    const form = e.currentTarget as HTMLFormElement;
    const formData = new FormData(form);

    // Honeypot check: if the hidden field has a value, it's likely a bot.
    const honeypot = formData.get("hp-field");
    if (honeypot) {
      setBanner({
        show: true,
        message: "Bot detected",
        type: "error",
      });
      setTimeout(() => {
        setBanner((prev) => ({ ...prev, show: false }));
      }, 3000);
      return;
    }

    // Time based anti-bot check:
    // Read the timestamp from the hidden field and ensure at least 3 seconds have passed.
    const timestampStr = formData.get("timestamp") as string;
    const timestamp = parseInt(timestampStr, 10);
    if (Date.now() - timestamp < 3000) {
      setBanner({
        show: true,
        message: "Please take your time filling out the form.",
        type: "error",
      });
      setTimeout(() => {
        setBanner((prev) => ({ ...prev, show: false }));
      }, 3000);
      return;
    }

    const data: ContactFormData = {
      name: formData.get("name") as string,
      email: formData.get("email") as string,
      message: formData.get("message") as string,
    };

    const jsonData = JSON.stringify(data);

    const submitButton = form.querySelector("button[type='submit']");
    if (submitButton) {
      submitButton.setAttribute("disabled", "true");
      submitButton.textContent = "Sending...";

      const response = await sendEmail(jsonData);
      if (response.success) {
        form.reset();
        submitButton.textContent = "Sent!";
        setTimeout(() => {
          submitButton.removeAttribute("disabled");
          submitButton.textContent = "Send";
        }, 2000);
      }
      setBanner({
        show: true,
        message: response.message,
        type: response.success ? "success" : "error",
      });
      setTimeout(() => {
        setBanner((prev) => ({ ...prev, show: false }));
      }, 3000);
    }
  }

  return (
    <section
      id="contact"
      className={`p-10 ${isVisible ? "animate-fly-in" : "opacity-0"}`}
    >
      <h2 className="text-3xl font-bold text-center text-gray-800 dark:text-white">
        Contact Me
      </h2>
      <div className="flex flex-col items-center p-8 bg-gradient-to-br from-white/60 to-white/30 backdrop-blur-lg rounded-2xl shadow-xl max-w-lg mx-auto mt-6 relative">
        {banner.show && (
          <div
            className={`absolute top-0 left-0 right-0 text-white text-center py-2 rounded-2xl animate-fade-out ${
              banner.type === "success" ? "bg-green-500" : "bg-red-500"
            }`}
          >
            {banner.message}
          </div>
        )}
        <form className="w-full space-y-4" onSubmit={onSubmit}>
          {/* Honeypot field: should remain empty */}
          <input
            type="text"
            name="hp-field"
            style={{ display: "none" }}
            autoComplete="off"
          />
          {/* Hidden timestamp field to check how fast the form was filled */}
          <input
            type="hidden"
            name="timestamp"
            value={formLoadedTimestamp.toString()}
          />
          <input
            type="text"
            name="name"
            placeholder="Name"
            className="w-full p-2 border rounded dark:text-white"
            required
          />
          <input
            type="email"
            name="email"
            placeholder="Email"
            className="w-full p-2 border rounded dark:text-white"
            required
          />
          <textarea
            name="message"
            placeholder="Message"
            className="w-full p-2 border rounded dark:text-white"
            rows={5}
            required
          ></textarea>
          <button
            type="submit"
            className="w-full p-2 text-white bg-gradient-to-r from-blue-500 to-purple-500 rounded hover:from-blue-600 hover:to-purple-600 transition"
          >
            Send
          </button>
        </form>
      </div>
    </section>
  );
}
