"use client";

import { useEffect, useState } from "react";
import { toast } from "react-toastify";

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

const DownloadBrochureModal = ({
  isOpen,
  onClose,
}: DownloadBrochureModalProps) => {
  const [shouldRender, setShouldRender] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [formData, setFormData] = useState({
    email: "",
    phone: "",
  });

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

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

    // Form validation
    if (!formData.email.trim()) {
      toast.error("Please enter your email address");
      return;
    }

    if (!formData.phone.trim()) {
      toast.error("Please enter your phone number");
      return;
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      toast.error("Please enter a valid email address");
      return;
    }

    try {
      // Simulate API call - replace with actual API endpoint
      // const response = await fetch('/api/download-brochure', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify(formData),
      // });

      // if (!response.ok) {
      //   throw new Error('Failed to submit');
      // }

      // Simulate API delay
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Success - show toast and close modal
      toast.success(
        "Request submitted successfully! We'll send you the brochure shortly."
      );

      // Reset form
      setFormData({ email: "", phone: "" });

      // Close modal after a short delay to allow toast to be visible
      setTimeout(() => {
        onClose();
      }, 100);
    } catch (error) {
      // Error - show toast but keep modal open
      toast.error("Something went wrong. Please try again later.");
      console.error("Form submission error:", error);
    }
  };

  // Handle mount/unmount with animation
  useEffect(() => {
    if (isOpen) {
      setShouldRender(true);
      const timer = setTimeout(() => setIsAnimating(true), 10);
      return () => clearTimeout(timer);
    } else {
      setIsAnimating(false);
      const timer = setTimeout(() => setShouldRender(false), 500);
      return () => clearTimeout(timer);
    }
  }, [isOpen]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }
    return () => {
      document.body.style.overflow = "unset";
    };
  }, [isOpen]);

  // Close on Escape key
  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;

  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}
    >
      {/* Backdrop - blur is applied immediately without transition to prevent layout shift */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm [backdrop-filter:blur(4px)]"
        style={{ willChange: "opacity" }}
      />

      {/* Modal Panel - Responsive sizing */}
      <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()}
      >
        {/* Close Button */}
        <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>

        {/* Content */}
        <form
          onSubmit={handleSubmit}
          className="p-8 sm:p-10 md:p-12 lg:p-14 xl:p-16"
        >
          {/* Email Input */}
          <div className="mb-8 sm:mb-10 md:mb-12">
            <input
              type="email"
              name="email"
              value={formData.email}
              onChange={handleInputChange}
              placeholder="Your Email"
              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>

          {/* Phone Input */}
          <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>

          {/* Send Button */}
          <div className="flex justify-center">
            <button
              type="submit"
              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"
            >
              Send
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default DownloadBrochureModal;
