"use client";

import { useState, useRef, useEffect } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination, Autoplay, Navigation } from "swiper/modules";
import "swiper/css";
import "swiper/css/pagination";
import { formattedPrice } from "@/utils";
import Link from "next/link";
import QuickAddPopup from "@/app/(root-layout)/products/_components/QuickAddPopup";
import LeadFormDialog from "./LeadFormDialog";
import { apiCall } from "@/utils/callApi";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import DefaultImage from "@/app/admin/_components/Defaultimage";

const ProductRow = ({ title, products }: any) => {
  const router = useRouter();
  const [popupState, setPopupState] = useState<{
    show: boolean;
    product: any;
    position: { top: number; left: number };
  }>({
    show: false,
    product: null,
    position: { top: 0, left: 0 },
  });
  const [showLeadModal, setShowLeadModal] = useState(false);
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    name: "",
    phone_number: "",
    // state: "",
    // city: "",
    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 buttonRefs = useRef<{ [key: string]: HTMLButtonElement | null }>({});
  const popupRef = useRef<HTMLDivElement | null>(null);

  const handleLeadSubmit = async (e: React.FormEvent, product: any) => {
    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;
    }

    setLoading(true);

    try {
      const response = await apiCall<any>("/clientapi/leadsebmit", {
        method: "POST",
        body: {
          name: formData.name.trim(),
          phone_number: formData.phone_number.trim(),
          // state: formData.state.trim(),
          // city: formData.city.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: "",
          // state: "",
          // city: "",
          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() === "") {
          // optional field, no validation
          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 = (
    product: any,
    event: React.MouseEvent,
    index: number,
  ) => {
    const button = buttonRefs.current[`cart-btn-${index}`];
    if (!button) return;

    const rect = button.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;
    }

    setPopupState({
      show: true,
      product: product,
      position: {
        top: rect.top - 10,
        left: left,
      },
    });
  };

  // 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 any cart button
      Object.values(buttonRefs.current).forEach((button) => {
        if (button && button.contains(target)) {
          isOutsideButton = false;
        }
      });

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

      if (isOutsideButton && isOutsidePopup) {
        setPopupState((prev) => ({ ...prev, show: false }));
      }
    };

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

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

  // Get product image (first image from variants or defaultImage)
  const getProductImage = (product: any) => {
    if (product.defaultImage) return product.defaultImage;
    if (product.variants?.[0]?.images?.[0]?.url)
      return product.variants[0].images[0].url;
    if (product.images?.[0]) return product.images[0];
    return "/images/placeholder.jpg";
  };

  // Get product price
  const getProductPrice = (product: any) => {
    return product.price || product.minPrice || 0;
  };

  // Get original price
  const getOriginalPrice = (product: any) => {
    return product.productprice > product.price
      ? product.productprice
      : product.price;
  };

  return (
    <>
      <section className="productcontainer">
        <div className="container-xxl container mx-1 px-3">
          <div className="-mx-3 flex flex-wrap">
            <div className="w-full px-3">
              <div className="section-heading mb-8 md:text-center">
                <h2 className="text-3xl font-bold">{title}</h2>
              </div>
            </div>
          </div>
          <div className="-mx-3 flex flex-wrap">
            <div className="relative w-full px-3">
              <Swiper
                modules={[Navigation, Autoplay]}
                loop={products?.length > 4}
                speed={700}
                autoplay={{
                  delay: 3000,
                  disableOnInteraction: false,
                  pauseOnMouseEnter: true,
                }}
                navigation={{
                  nextEl: ".swiper-button-next-new-arrival",
                  prevEl: ".swiper-button-prev-new-arrival",
                }}
                spaceBetween={20}
                breakpoints={{
                  100: {
                    slidesPerView: 1,
                    spaceBetween: 5,
                  },
                  260: {
                    slidesPerView: 2,
                    spaceBetween: 5,
                  },
                  370: {
                    slidesPerView: 2,
                    spaceBetween: 10,
                  },
                  574: {
                    slidesPerView: 2,
                    spaceBetween: 12,
                  },
                  768: {
                    slidesPerView: 3,
                    spaceBetween: 15,
                  },
                  992: {
                    slidesPerView: 4,
                    spaceBetween: 15,
                  },
                  1200: {
                    slidesPerView: 4,
                    spaceBetween: 20,
                  },
                  1400: {
                    slidesPerView: 4,
                    spaceBetween: 20,
                  },
                  1700: {
                    slidesPerView: 4,
                    spaceBetween: 20,
                  },
                }}
              >
                {products?.map((product: any, index: number) => (
                  <SwiperSlide key={index}>
                    <div className="productbx overflow-hidden">
                      <div className="productbximg relative overflow-hidden">
                        {/* Discount Badge */}
                        {product?.productprice > product?.price && (
                          <div className="discountbx absolute left-2 top-2 z-10">
                            <span className="discounttxt rounded bg-red-500 px-2 py-1 text-xs text-white">
                              {Math.round(
                                ((product.productprice - product.price) /
                                  product.productprice) *
                                  100,
                              )}
                              % Off
                            </span>
                          </div>
                        )}
                        <Link href={`/productdetails/${product.slug}`}>
                          {getProductImage(product) ? (
                            <img
                              alt={product.name}
                              src={getProductImage(product)}
                              className="max-h-350px w-full object-cover transition duration-300 hover:scale-105"
                            />
                          ) : (
                            <DefaultImage />
                          )}
                        </Link>
                      </div>

                      <div className="productcontent">
                        <div className="mb-2 flex justify-between gap-2">
                          <h3 className="line-clamp-2">
                            <Link href={`/productdetails/${product.slug}`}>
                              {product.name}
                            </Link>
                          </h3>
                          <button
                            ref={(el) => {
                              buttonRefs.current[`cart-btn-${index}`] = el;
                            }}
                            className="productcart"
                            type="button"
                            onClick={(e) => handleCartClick(product, e, index)}
                          >
                            <i className="icon icon-cart-bag"></i>

                            {/* Quick Add Popup */}
                            {popupState.show &&
                              popupState.product?._id === product._id && (
                                <QuickAddPopup
                                  popupRef={popupRef}
                                  product={{
                                    _id: popupState.product._id,
                                    name: popupState.product.name,
                                    image: getProductImage(popupState.product),
                                    price: getProductPrice(popupState.product),
                                    originalPrice: getOriginalPrice(
                                      popupState?.product,
                                    ),
                                    skus: popupState.product.skus ?? [],
                                    slug: popupState.product.slug,
                                    variants: popupState.product.variants || [],
                                    totalQuantity:
                                      popupState.product.totalQuantity ?? 0,
                                  }}
                                  onClose={() =>
                                    setPopupState((prev) => ({
                                      ...prev,
                                      show: false,
                                    }))
                                  }
                                  setShowLeadModal={setShowLeadModal}
                                  position={popupState.position}
                                />
                              )}
                          </button>

                          <LeadFormDialog
                            open={showLeadModal}
                            onOpenChange={setShowLeadModal}
                            formData={formData}
                            setFormData={setFormData}
                            checkValidation={checkValidation}
                            validationError={validationError}
                            location={"others"}
                            handleSubmit={(e: any) =>
                              handleLeadSubmit(e, product)
                            }
                            loading={loading}
                          />
                        </div>

                        <div className="flex justify-between gap-2">
                          {product.price &&
                            product.productprice &&
                            product.productprice > product.price && (
                              <span className="crossprice text-gray-400 line-through">
                                {formattedPrice(getOriginalPrice(product))}
                              </span>
                            )}
                          <span className="price">
                            {formattedPrice(getProductPrice(product))}
                          </span>
                        </div>
                      </div>
                    </div>
                  </SwiperSlide>
                ))}
              </Swiper>

              {/* Navigation */}
              {products.length >= 5 && (
                <div className="swiper-nav mt-0">
                  <div className="swiper-button-prev swiper-button-prev-new-arrival"></div>
                  <div className="swiper-button-next swiper-button-next-new-arrival"></div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>
    </>
  );
};

export default ProductRow;
