"use client";

import { useState } from "react";
import Image from "next/image";
import { contactFormData } from "@/data/contact/contactFormData";
import ContactMap from "./ContactMap";

export default function ContactForm() {
  const { title, description, button, fields, animation } = contactFormData;
  const [formData, setFormData] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [message, setMessage] = useState("");
  const [messageType, setMessageType] = useState(""); // "success" or "error"

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsSubmitting(true);
    setMessage("");

    try {
      const response = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          access_key: "YOUR_ACCESS_KEY_HERE", // User needs to replace this
          ...formData,
        }),
      });

      const result = await response.json();

      if (result.success) {
        setMessage("Thank you for your message! We'll get back to you soon.");
        setMessageType("success");
        setFormData({});
        e.currentTarget.reset();
      } else {
        // Check if the error is related to missing access key
        if (
          result.message &&
          (result.message.includes("access key") ||
            result.message.includes("Access key"))
        ) {
          setMessage(
            "You need to add your access key from web3forms.com to make this form functional.",
          );
        } else {
          setMessage(
            result.message || "Something went wrong. Please try again later.",
          );
        }
        setMessageType("error");
      }
    } catch (error: unknown) {
      // Handle network errors or other issues
      setMessage(
        "You need to add your access key from web3forms.com to make this form functional.",
      );
      setMessageType("error");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <section className="form-sec space-bottom">
      <div className="carousel-container">
        <div className="row">
          <div className="col-lg-6">
            <ContactMap />
          </div>

          <div className="col-lg-6">
            <div
              className="form-content"
              data-aos={animation.animation}
              data-aos-duration={animation.duration}
              data-aos-delay={animation.delay}
            >
              <h3 className="title">{title}</h3>
              <p>{description}</p>

              {/* Message Display */}
              {message && (
                <div
                  className={`alert alert-${messageType}`}
                  style={{
                    padding: "12px 16px",
                    borderRadius: "8px",
                    marginBottom: "20px",
                    backgroundColor:
                      messageType === "success" ? "#d4edda" : "#f8d7da",
                    color: messageType === "success" ? "#155724" : "#721c24",
                    border: `1px solid ${messageType === "success" ? "#c3e6cb" : "#f5c6cb"}`,
                  }}
                >
                  {message}
                </div>
              )}

              <form className="contact-form" onSubmit={handleSubmit}>
                <div className="row">
                  {fields.map((field) => (
                    <div key={field.id} className={field.colWidth}>
                      <div className="form-group">
                        {field.type === "textarea" ? (
                          <textarea
                            name={field.id}
                            placeholder={field.placeholder}
                            required={field.required}
                            onChange={handleInputChange}
                            disabled={isSubmitting}
                          />
                        ) : (
                          <input
                            type={field.type}
                            name={field.id}
                            placeholder={field.placeholder}
                            required={field.required}
                            onChange={handleInputChange}
                            disabled={isSubmitting}
                          />
                        )}
                      </div>
                    </div>
                  ))}
                  <div className="col-lg-12">
                    <div className="form-group mb-0">
                      <button
                        type="submit"
                        className={button.className}
                        disabled={isSubmitting}
                      >
                        {isSubmitting ? "Sending..." : button.text}
                        <span>
                          <Image
                            src={button.icon.src}
                            alt={button.icon.alt}
                            width={button.icon.width}
                            height={button.icon.height}
                          />
                        </span>
                      </button>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
