"use client";

import { useState } from "react";
import { useTheme } from "next-themes";
import { FaCheckCircle, FaExclamationCircle } from "react-icons/fa";

const NewsLatterBox = () => {
  const { theme } = useTheme();

  // 🔷 1. स्टेट में 'name' भी शामिल किया ताकि डेटा सही से कैप्चर हो
  const [formData, setFormData] = useState({
    name: "",
    companyName: "",
    email: "",
    phone: "",
    message: "",
  });

  const [status, setStatus] = useState<{
    type: "idle" | "loading" | "success" | "error";
    message: string;
  }>({ type: "idle", message: "" });

  // 🔷 2. इनपुट चेंज हैंडलर (HTML id के आधार पर स्टेट की सही 'key' अपडेट करेगा)
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { id, value } = e.target;
    const stateKey = id === "company-name" ? "companyName" : id;
    setFormData((prev) => ({ ...prev, [stateKey]: value }));
  };

  // 🔷 3. फॉर्म सबमिशन लॉजिक
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setStatus({ type: "loading", message: "Sending your message..." });

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        setStatus({
          type: "success",
          message: "Thank you! Your message has been sent successfully to our team.",
        });

        // फॉर्म डेटा रीसेट करें
        setFormData({ name: "", companyName: "", email: "", phone: "", message: "" });

        // 2 सेकंड बाद पेज रिफ्रेश ताकि यूजर रिस्पॉन्स देख सके
        setTimeout(() => {
          window.location.reload();
        }, 2000);
      } else {
        throw new Error(data.message || "Something went wrong.");
      }
    } catch (error: any) {
      setStatus({
        type: "error",
        message: error.message || "Failed to send message. Please try again later.",
      });
    }
  };

  return (
    <div className="shadow-three relative z-10 overflow-hidden rounded-2xl bg-white p-8 dark:bg-white sm:p-11">

      {/* Heading */}
      <h3 className="mb-4 text-3xl font-bold text-gray-900 dark:text-dark">
        Get In Touch
      </h3>

      {/* 🔷 4. स्टेटस अलर्ट बॉक्स (यूजर फीडबैक के लिए) */}
      {status.type === "success" && (
        <div className="mb-5 flex items-center gap-2 rounded-xl bg-emerald-50 p-4 text-emerald-800 border border-emerald-200 text-sm font-semibold">
          <FaCheckCircle className="text-emerald-600 text-lg shrink-0" />
          <p>{status.message}</p>
        </div>
      )}

      {status.type === "error" && (
        <div className="mb-5 flex items-center gap-2 rounded-xl bg-rose-50 p-4 text-rose-800 border border-rose-200 text-sm font-semibold">
          <FaExclamationCircle className="text-rose-600 text-lg shrink-0" />
          <p>{status.message}</p>
        </div>
      )}

      {/* 🔷 5. फॉर्म टैग में onSubmit हैंडलर जोड़ा */}
      <form className="space-y-5" onSubmit={handleSubmit}>

        {/* Name */}
        <input
          id="name"
          type="text"
          required
          value={formData.name}
          onChange={handleChange}
          placeholder="Enter your name"
          className="w-full rounded-xl border border-gray-200 bg-gray-50 px-5 py-3 text-base outline-none transition focus:border-[#db2516] focus:bg-white dark:border-gray-700 dark:bg-[#0b4755] dark:text-white"
        />

        {/* Company */}
        <input
          id="company-name"
          type="text"
          required
          value={formData.companyName}
          onChange={handleChange}
          placeholder="Enter company name"
          className="w-full rounded-xl border border-gray-200 bg-gray-50 px-5 py-3 text-base outline-none transition focus:border-[#db2516] focus:bg-white dark:border-gray-700 dark:bg-[#0b4755] dark:text-white"
        />

        {/* Email */}
        <input
          id="email"
          type="email"
          required
          value={formData.email}
          onChange={handleChange}
          placeholder="Enter your email"
          className="w-full rounded-xl border border-gray-200 bg-gray-50 px-5 py-3 text-base outline-none transition focus:border-[#db2516] focus:bg-white dark:border-gray-700 dark:bg-[#0b4755] dark:text-white"
        />

        {/* Contact (Validation के साथ) */}
        <input
          id="phone"
          type="tel"
          required
          pattern="[0-9]{10}"
          title="Please enter a valid 10-digit phone number"
          value={formData.phone}
          onChange={handleChange}
          placeholder="Enter your 10-digit contact number"
          className="w-full rounded-xl border border-gray-200 bg-gray-50 px-5 py-3 text-base outline-none transition focus:border-[#db2516] focus:bg-white dark:border-gray-700 dark:bg-[#0b4755] dark:text-white"
        />

        {/* Message */}
        <textarea
          id="message"
          rows={4}
          required
          value={formData.message}
          onChange={handleChange}
          placeholder="Enter your message"
          className="w-full rounded-xl border border-gray-200 bg-gray-50 px-5 py-3 text-base outline-none transition focus:border-[#db2516] focus:bg-white dark:border-gray-700 dark:bg-[#0b4755] dark:text-white"
        ></textarea>

        {/* Button (Loading स्टेट हैंडलिंग के साथ) */}
        <button
          type="submit"
          disabled={status.type === "loading"}
          className={`w-full rounded-xl bg-[#db2516] px-6 py-4 text-base font-semibold text-white transition duration-300 hover:scale-[1.02] hover:bg-black ${status.type === "loading" ? "opacity-60 cursor-not-allowed" : ""
            }`}
        >
          {status.type === "loading" ? "Sending..." : "Send Message"}
        </button>

      </form>

      {/* Decorative Shapes */}
      <div>
        <span className="absolute left-2 top-7 opacity-40">
          <svg width="57" height="65" viewBox="0 0 57 65" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path opacity="0.5" d="M0.407629 15.9573L39.1541 64.0714L56.4489 0.160793L0.407629 15.9573Z" fill={theme === "light" ? "#db2516" : "#fff"} />
          </svg>
        </span>

        <span className="absolute bottom-10 right-5 opacity-20">
          <svg width="90" height="90" viewBox="0 0 90 90" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="45" cy="45" r="45" fill={theme === "light" ? "#db2516" : "#fff"} />
          </svg>
        </span>
      </div>

    </div>
  );
};

export default NewsLatterBox;