"use client";

import React, { useEffect, useRef, useState } from "react";
import Swiper from "swiper";
import "swiper/css";
import "swiper/css/navigation";
import QuickAddPopup from "../../products/_components/QuickAddPopup";
import LeadFormDialog from "@/components/frontend-pages/home/LeadFormDialog";
import { toast } from "sonner";
import { apiCall } from "@/utils/callApi";
import { useRouter } from "next/navigation";

interface RelatedProductsProps {
  currentProductId: string;
  category?: string;
}

export default function RelatedProducts({
  currentProductId,
  category,
}: RelatedProductsProps) {
  const swiperRef = useRef<HTMLDivElement>(null);
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchRelatedProducts = async () => {
      try {
        const url = category
          ? `/clientapi/products?category=${category}&limit=8`
          : `/clientapi/products?limit=8`;

        const response = await fetch(url);
        const result = await response.json();

        if (result.success && result.data) {
          const filtered = result.data.filter(
            (p: any) => p._id !== currentProductId,
          );
          setProducts(filtered.slice(0, 8));
        }
      } catch (error) {
        console.error("Error fetching related products:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchRelatedProducts();
  }, [currentProductId, category]);

  useEffect(() => {
    if (swiperRef.current && products.length > 0) {
      const swiper = new Swiper(swiperRef.current, {
        slidesPerView: 1,
        spaceBetween: 20,
        navigation: {
          nextEl: ".swiper-button-next-reception-collections",
          prevEl: ".swiper-button-prev-reception-collections",
        },
        breakpoints: {
          640: { slidesPerView: 2 },
          768: { slidesPerView: 3 },
          1024: { slidesPerView: 4 },
        },
      });

      return () => swiper.destroy();
    }
  }, [products]);

  if (loading) {
    return (
      <section className="productcontainer">
        <div className="container-xxl container px-3">
          <div className="section-heading sm:text-center">
            <h2>You May Also Like</h2>
          </div>
          <div className="py-10 text-center">
            <p>Loading related products...</p>
          </div>
        </div>
      </section>
    );
  }

  if (products.length === 0) {
    return null;
  }

  return (
    <section className="productcontainer">
      <div className="container-xxl container px-3">
        <div className="section-heading sm:text-center">
          <h2>You May Also Like</h2>
        </div>
        <div className="-mx-n3 flex flex-wrap">
          <div className="relative w-full px-3">
            <div ref={swiperRef} className="swiper">
              <div className="swiper-wrapper">
                {products.map((product) => (
                  <div className="swiper-slide" key={product._id}>
                    <ProductCard product={product} />
                  </div>
                ))}
              </div>
            </div>
            {products.length >= 5 && (
              <div className="swiper-nav">
                <div className="swiper-button-prev swiper-button-prev-reception-collections"></div>
                <div className="swiper-button-next swiper-button-next-reception-collections"></div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function ProductCard({ product }: { product: any }) {
  const router = useRouter();
  const [showPopup, setShowPopup] = useState(false);
  const [popupPosition, setPopupPosition] = useState({
    top: 0,
    left: 0,
  });
  const popupRef = useRef<HTMLDivElement | null>(null);
  const [showLeadModal, setShowLeadModal] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    phone_number: "",
    address: "",
    email: "",
  });
  const [validationError, setValidationError] = useState<{
    phone_number: string | null;
    name: string | null;
    address: string | null;
    email: string | null;
  }>({
    phone_number: null,
    name: null,
    address: null,
    email: null,
  });
  const [loading, setLoading] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);

  const price = product.price || product.minPrice || 0;
  const originalPrice = product.productprice;
  const discount = originalPrice
    ? Math.round(((originalPrice - price) / originalPrice) * 100)
    : 0;
  const image =
    product.defaultImage ||
    product.variants?.[0]?.images?.[0]?.url ||
    "/images/placeholder.jpg";

  // Close popup when clicking outside
  useEffect(() => {
    const handleOutsideClick = (event: MouseEvent) => {
      const target = event.target as Node;

      // Check if click is outside both the cart button and the popup
      let isOutsidePopup = true;
      let isOutsideButton = true;

      // Check if click is on the cart button
      if (buttonRef.current && buttonRef.current.contains(target)) {
        isOutsideButton = false;
      }

      // Check if click is on popup
      if (popupRef.current && popupRef.current.contains(target)) {
        isOutsidePopup = false;
      }

      if (isOutsideButton && isOutsidePopup && showPopup) {
        setShowPopup(false);
      }
    };

    if (showPopup) {
      document.addEventListener("mousedown", handleOutsideClick);
    }

    return () => {
      document.removeEventListener("mousedown", handleOutsideClick);
    };
  }, [showPopup]);

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

    // Name validation
    if (!formData.name.trim()) {
      toast.error("Name is required");
      return;
    }

    // Phone validation
    if (!formData.phone_number.trim()) {
      toast.error("Phone number is required");
      return;
    }

    if (!/^\d{10}$/.test(formData.phone_number.trim())) {
      toast.error("Please enter a valid 10 digit mobile number");
      return;
    }

    if (formData?.email && checkValidation("email", formData.email)) {
      toast.error("Please enter a valid email address");
      return;
    }

    setLoading(true);

    try {
      const response = await apiCall<any>("/clientapi/leadsebmit", {
        method: "POST",
        body: {
          name: formData.name.trim(),
          phone_number: formData.phone_number.trim(),
          address: formData.address.trim(),
          email: formData.email.trim(),
          product_id: product._id,
          product_name: product.name,
          source: "product_list_card",
          products: [product],
        },
      });

      if (response.error) {
        toast.error(response.error);
        return;
      }

      if (response.data?.success) {
        localStorage.setItem("lead", JSON.stringify(response.data.data));

        toast.success(
          response.data.message ||
            "Thank you! Our team will contact you shortly",
        );
        setShowLeadModal(false);
        setFormData({
          name: "",
          phone_number: "",
          address: "",
          email: "",
        });
        router.push("/thankingyou");
      } else {
        toast.error(response.data?.message || "Failed to submit inquiry");
      }
    } catch (error) {
      console.error(error);
      toast.error("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const checkValidation = (key: string, value: string) => {
    let error: string | null = null;

    switch (key) {
      case "phone_number": {
        const phoneRegex = /^[6-9]\d{9}$/;
        if (!phoneRegex.test(value)) {
          error = "Invalid Indian phone number";
        }
        break;
      }

      case "name": {
        const usernameRegex = /^[A-Za-z][A-Za-z0-9_ ]{2,23}$/;
        if (value.length < 3 || value.length > 20) {
          error = "Username must be 3–25 characters";
        } else if (!usernameRegex.test(value)) {
          error =
            "Name must start with a letter and contain only letters, numbers, and _";
        }
        break;
      }

      case "address": {
        const cityRegex = /^[A-Za-z\s.\-', ]{2,50}$/;
        if (value.length < 2 || value.length > 500) {
          error = "Location must be 2–500 characters";
        } else if (!cityRegex.test(value)) {
          error = "Location can only contain letters, spaces, dots, hyphens";
        }
        break;
      }

      case "email": {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!value || value.trim() === "") {
          break;
        }
        if (value.length > 500) {
          error = "Email must be less than 500 characters";
        } else if (!emailRegex.test(value)) {
          error = "Please enter a valid email address";
        }
        break;
      }

      default:
        error = null;
    }

    setValidationError((prev) => ({
      ...prev,
      [key]: error,
    }));

    return error;
  };

  const handleCartClick = (e: React.MouseEvent) => {
    e.stopPropagation();

    if (!buttonRef.current) return;

    const rect = buttonRef.current.getBoundingClientRect();
    const popupWidth = 300;

    let left = rect.right - popupWidth;
    if (left < 10) {
      left = 10;
    }
    if (left + popupWidth > window.innerWidth - 10) {
      left = window.innerWidth - popupWidth - 10;
    }

    setPopupPosition({
      top: rect.top - 10,
      left,
    });

    // Toggle popup - close if already open, open if closed
    setShowPopup((prev) => !prev);
  };

  // Function to close popup and handle lead modal
  const handleClosePopup = () => {
    setShowPopup(false);
  };

  return (
    <div className="productbx">
      <div className="productbximg relative">
        <a href={`/productdetails/${product.slug}`}>
          <img src={image} alt={product.name} />
        </a>
        {discount > 0 && (
          <div className="discountbx absolute left-2 top-2">
            <span className="discounttxt">{discount}% Off</span>
          </div>
        )}
      </div>
      <div className="productcontent">
        <div className="mb-2 flex justify-between gap-2">
          <h3>
            <a href={`/productdetails/${product.slug}`}>{product.name}</a>
          </h3>
          <button
            ref={buttonRef}
            className="productcart relative"
            type="button"
            onClick={handleCartClick}
          >
            <i className="icon icon-cart-bag"></i>
          </button>

          {/* Popup rendered outside the button */}
          {showPopup && (
            <QuickAddPopup
              popupRef={popupRef}
              product={{
                _id: product._id,
                name: product.name,
                image: product.defaultImage,
                price: product.price,
                originalPrice: product.productprice,
                skus: product.skus ?? [],
                slug: product.slug,
                variants: product.variants || [],
                totalQuantity: product?.totalQuantity ?? 0,
              }}
              onClose={handleClosePopup}
              position={popupPosition}
              setShowLeadModal={setShowLeadModal}
              setShowPopup={setShowPopup}
            />
          )}
        </div>
        <div className="flex justify-between gap-2">
          {originalPrice && originalPrice > price && (
            <span className="crossprice">
              ₹{originalPrice.toLocaleString("en-IN")}
            </span>
          )}
          <span className="price">₹{price.toLocaleString("en-IN")}</span>
        </div>
      </div>

      <LeadFormDialog
        open={showLeadModal}
        onOpenChange={setShowLeadModal}
        formData={formData}
        setFormData={setFormData}
        checkValidation={checkValidation}
        validationError={validationError}
        location={"others"}
        handleSubmit={handleLeadSubmit}
        loading={loading}
      />
    </div>
  );
}
