"use client";

import { useEffect, useState } from "react";

interface DownloadBrochureModalProps {
  isOpen: boolean;
  onClose: () => void;
  propertyKey?: string;
}

const BROCHURE_THANK_YOU =
  "Your request has been sent. Our sales team will email you the brochure — please wait a few minutes.";

const panelPadding =
  "p-8 sm:p-10 md:p-12 lg:p-14 xl:p-16 min-h-[280px] sm:min-h-[320px]";

const DownloadBrochureModal = ({
  isOpen,
  onClose,
  propertyKey = "unknown-property",
}: DownloadBrochureModalProps) => {
  const [shouldRender, setShouldRender] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formData, setFormData] = useState({
    email: "",
    phone: "",
  });
  const [feedback, setFeedback] = useState<{
    type: "error" | "success";
    text: string;
  } | null>(null);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
    if (feedback?.type === "error") setFeedback(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setFeedback(null);

    if (!formData.email.trim()) {
      setFeedback({
        type: "error",
        text: "Please enter your email address.",
      });
      return;
    }

    if (!formData.phone.trim()) {
      setFeedback({
        type: "error",
        text: "Please enter your phone number.",
      });
      return;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      setFeedback({
        type: "error",
        text: "Please enter a valid email address.",
      });
      return;
    }

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

      let result: { message?: string } = {};
      try {
        result = await response.json();
      } catch {
        // ignore parse errors
      }

      const message =
        response.ok && result?.message ? result.message : BROCHURE_THANK_YOU;

      setFeedback({ type: "success", text: message });
      setFormData({ email: "", phone: "" });
    } catch (error) {
      console.error("Form submission error:", error);
      setFeedback({ type: "success", text: BROCHURE_THANK_YOU });
      setFormData({ email: "", phone: "" });
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    if (isOpen) {
      setShouldRender(true);
      setFeedback(null);
      const timer = setTimeout(() => setIsAnimating(true), 10);
      return () => clearTimeout(timer);
    } else {
      setIsAnimating(false);
      const timer = setTimeout(() => setShouldRender(false), 500);
      return () => clearTimeout(timer);
    }
  }, [isOpen]);

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }
    return () => {
      document.body.style.overflow = "unset";
    };
  }, [isOpen]);

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape" && isOpen) {
        onClose();
      }
    };
    window.addEventListener("keydown", handleEscape);
    return () => window.removeEventListener("keydown", handleEscape);
  }, [isOpen, onClose]);

  if (!shouldRender) return null;

  const isSuccess = feedback?.type === "success";

  return (
    <div
      className={`fixed inset-0 z-50 flex items-center justify-center transition-opacity duration-300 ${
        isAnimating ? "opacity-100" : "opacity-0 pointer-events-none"
      }`}
      onClick={onClose}
    >
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm [backdrop-filter:blur(4px)]"
        style={{ willChange: "opacity" }}
      />

      <div
        className={`relative bg-white shadow-2xl transform transition-all duration-500 ease-out
          w-[90vw] h-auto max-h-[90vh]
          sm:w-[80vw] sm:max-w-[500px]
          md:w-[60vw] md:max-w-[550px]
          lg:w-[45vw] lg:max-w-[600px]
          xl:w-[35vw] xl:max-w-[650px]
          ${
            isAnimating
              ? "scale-100 opacity-100"
              : "scale-95 opacity-0 pointer-events-none"
          }`}
        onClick={(e) => e.stopPropagation()}
      >
        <button
          onClick={onClose}
          className="absolute top-4 right-4 p-2 text-gray-400 hover:text-gray-600 transition-colors duration-300 z-10"
          aria-label="Close modal"
        >
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path
              d="M18 6L6 18M6 6L18 18"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
        </button>

        {isSuccess ? (
          <div
            className={`${panelPadding} flex flex-col items-center justify-center text-center`}
          >
            <p
              role="status"
              className="max-w-md text-sm sm:text-[15px] font-light leading-relaxed tracking-wide text-gray-600"
            >
              {feedback.text}
            </p>
            <button
              type="button"
              onClick={onClose}
              className="mt-10 sm:mt-12 px-12 sm:px-14 md:px-16 py-3 sm:py-3.5 md:py-4 bg-[#333333] text-white text-sm sm:text-base tracking-wide hover:bg-[#444444] transition-colors duration-300"
            >
              Close
            </button>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className={panelPadding}>
            <div className="mb-8 sm:mb-10 md:mb-12">
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleInputChange}
                placeholder="Your Email"
                aria-invalid={feedback?.type === "error"}
                className="w-full bg-transparent text-gray-800 text-sm sm:text-base font-light tracking-wide py-3 border-b border-gray-300 placeholder-gray-400 focus:outline-none focus:border-gray-500 transition-colors duration-300"
              />
            </div>

            <div className="mb-10 sm:mb-12 md:mb-14">
              <input
                type="tel"
                name="phone"
                value={formData.phone}
                onChange={handleInputChange}
                placeholder="Your Phone Number"
                className="w-full bg-transparent text-gray-800 text-sm sm:text-base font-light tracking-wide py-3 border-b border-gray-300 placeholder-gray-400 focus:outline-none focus:border-gray-500 transition-colors duration-300"
              />
            </div>

            <div className="flex flex-col items-center">
              <button
                type="submit"
                disabled={isSubmitting}
                className="px-12 sm:px-14 md:px-16 py-3 sm:py-3.5 md:py-4 bg-[#333333] text-white text-sm sm:text-base tracking-wide hover:bg-[#444444] transition-colors duration-300 disabled:opacity-60 disabled:cursor-not-allowed"
              >
                {isSubmitting ? "Sending..." : "Send"}
              </button>

              {feedback?.type === "error" ? (
                <p
                  role="alert"
                  className="mt-6 max-w-md text-center text-sm sm:text-[15px] font-light leading-relaxed tracking-wide text-red-700/90"
                >
                  {feedback.text}
                </p>
              ) : null}
            </div>
          </form>
        )}
      </div>
    </div>
  );
};

export default DownloadBrochureModal;
