"use client";

import { BadgeQuestionMarkIcon } from "lucide-react";
import { useState, useRef, useEffect } from "react";
import QuickAddPopup from "./QuickAddPopup";
import LeadFormDialog from "@/components/frontend-pages/home/LeadFormDialog";
import { toast } from "sonner";
import { apiCall } from "@/utils/callApi";
import { useCart } from "@/hooks/useCart";
import { useRouter } from "next/navigation";
export type ProductListItem = {
  _id: string;
  name: string;
  slug: string;
  image: string;
  productprice: number;
  price: number;
  originalPrice: number;
  discount?: number;
  skus: any[];
  variants: any[];
  totalQuantity?: number;
  totalReviews?: any[];
  availableColors?: any[];
  availableSizes?: any[];
  wishlisted: boolean;
};

export default function ProductListCard({
  product,
  onWishListToggle,
  wishlistingId,
}: {
  product: ProductListItem;
  onWishListToggle: (product: any) => void;
  wishlistingId: string;
}) {
  // console.log(product);

  const [showPopup, setShowPopup] = useState(false);
  const [showLeadModal, setShowLeadModal] = useState(false);
  const [popupPosition, setPopupPosition] = useState({
    top: 0,
    left: 0,
  });
  const { addItem } = useCart();
  const router = useRouter();
  const buttonRef = useRef<HTMLButtonElement>(null);
  const popupRef = useRef<HTMLDivElement | null>(null);
  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 discount =
    product?.originalPrice && product?.price
      ? Math.round(
          ((product.originalPrice - product.price) / product.originalPrice) *
            100,
        )
      : 0;

  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(),
          // 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 = () => {
    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,
    });

    setShowPopup((prev) => !prev);
  };

  const noVariantsSendToInquiry = async (product: ProductListItem) => {
    try {
      const res = await addItem(product._id, "", 1);
      // console.log("REEEEEEES", res);
      if (res.data?.success) {
        toast.success(
          res.data?.data?.message || "Item added to cart successfully",
        );
      } else {
        toast.error(
          res?.error ||
            res?.data?.data?.message ||
            res?.data?.data?.error ||
            "Falied to add to cart",
        );
      }
    } catch (error: any) {
      console.error("Falied to add to cart", error);
      toast.error(
        error?.message || error?.data?.message || "Falied to add to cart",
      );
    }
  };

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

      if (
        buttonRef.current &&
        !buttonRef.current.contains(target) &&
        popupRef.current &&
        !popupRef.current.contains(target)
      ) {
        setShowPopup(false);
      }
    };

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

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

  return (
    <div className="productbx">
      <div className="productbximg">
        <div className="discountbx">
          {/* 
          <button
            className="wishlistbtn"
            aria-label="Wishlist"
            onClick={() => onWishListToggle?.(product)}
          >
            <Heart
              size={18}
              stroke={product.wishlisted ? "#e11d48" : "#0e0d0d"}
              fill={product.wishlisted ? "#e11d48" : "none"}
            />
          </button> */}
        </div>
        {discount > 0 && (
          <div className="discountbx absolute left-2 top-2">
            <span className="discounttxt">{discount}% Off</span>
          </div>
        )}
        <a href={`/productdetails/${product?.slug}`}>
          <img src={product?.image} alt={product?.name} />
        </a>
      </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"
            type="button"
            // onClick={() => {
            //   if(product.variants.length !== 0) handleCartClick()
            //   else {
            //       setShowLeadModal(true)
            //       noVariantsSendToInquiry(product)
            //   }
            // }}
            onClick={handleCartClick}
          >
            {/* {product.variants.length !==0 ?(<i className="icon icon-cart-bag"></i>):(
                <BadgeQuestionMarkIcon />
              )}                         */}
            <i className="icon icon-cart-bag"></i>
          </button>

          {/* {showPopup ? (
                product.variants.length !== 0 ? (
                  <QuickAddPopup
                    popupRef={popupRef}
                    product={{
                      _id: product._id,
                      name: product.name,
                      image: product.image,
                      price: product.price,
                      originalPrice: product.originalPrice,
                      skus: product.skus ?? [],
                      variants: product.variants || [],
                      totalQuantity: product?.totalQuantity ?? 0,
                    }}
                    onClose={() => setShowPopup(false)}
                    position={popupPosition}
                  />
                ) : ( <LeadFormDialog
                              open={showLeadModal}
                              onOpenChange={setShowLeadModal}
                              formData={formData}
                              setFormData={setFormData}
                              checkValidation={checkValidation}
                              validationError={validationError}
                
                              location={"home"}
                              handleSubmit={handleLeadSubmit}
                              loading={loading}
                            />
                          )
              ) : null} */}

          {showPopup && (
            <QuickAddPopup
              popupRef={popupRef}
              product={{
                _id: product._id,
                name: product.name,
                image: product.image,
                price: product.price,
                originalPrice: product.productprice,
                skus: product.skus ?? [],
                slug: product.slug,
                variants: product.variants || [],
                totalQuantity: product?.totalQuantity ?? 0,
              }}
              onClose={() => setShowPopup(false)}
              position={popupPosition}
              setShowLeadModal={setShowLeadModal}
              setShowPopup={setShowPopup}
            />
          )}

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

        <div className="flex justify-between gap-2">
          {product?.originalPrice && product.originalPrice > product.price &&<span className="crossprice">
            ₹{product?.originalPrice?.toLocaleString("en-IN")}
          </span>}

          <span className="price">
            ₹{product?.price?.toLocaleString("en-IN")}
          </span>
        </div>
      </div>
    </div>
  );
}
