"use client";

import { useState, useEffect, RefObject } from "react";
import { X, ShoppingBag, Check } from "lucide-react";
import { useCart } from "@/hooks/useCart";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { Tooltip } from "@/components/ui/tooltip";

type VariantSize = {
  _id: string;
  name: string;
  sortOrder: number;
  sku_id: string;
  price: {
    $numberDecimal: string;
  };
  quantity: number;
};

type Variant = {
  _id: string;
  name: string;
  images: any[];
  hexCode: string;
  sizes: VariantSize[];
};

type Props = {
  product: {
    _id: string;
    name: string;
    image: string;
    price: number;
    originalPrice: number;
    skus: any[];
    slug: string;
    variants: Variant[];
    totalQuantity: number;
  };

  onClose: () => void;

  position: {
    top: number;
    left: number;
  };

  popupRef: RefObject<HTMLDivElement | null>;
  setShowLeadModal?: React.Dispatch<React.SetStateAction<boolean>>;
  setShowPopup?: React.Dispatch<React.SetStateAction<boolean>>;
};

export default function QuickAddPopup({
  product,
  onClose,
  position,
  popupRef,
  setShowLeadModal,
  setShowPopup,
}: Props) {
  // console.log("^^^^", product);
  const router = useRouter();
  const { addItem, loading } = useCart();
  const [selectedColor, setSelectedColor] = useState<Variant | null>(null);
  const [selectedColorImage, setSelectedColorImage] = useState<string | null>(
    null,
  );
  const [selectedSkuId, setSelectedSkuId] = useState<string | null>(null);
  const [added, setAdded] = useState(false);

  const colors: Variant[] = product?.variants || [];
  const visibleColors = colors.slice(0, 4); // Size Code
  const remainingColors = colors.length - 4; // Size Code

  const hasColors = colors.length > 0;
  const availableSizes = selectedColor?.sizes || [];
  const visibleSizes = availableSizes.slice(0, 4); // Size Code
  const remainingSizes = availableSizes.length - 4; // Size Code

  // console.log('Color and sizes', colors, availableSizes)
  // Auto select first color and its first available size on mount
  useEffect(() => {
    if (hasColors && colors.length > 0 && !selectedColor) {
      const firstColor: any = colors[0];
      setSelectedColor(firstColor);
      setSelectedColorImage(firstColor?.images?.[0]?.url || null);
      // Auto select first available size for the first color
      if (firstColor.sizes && firstColor.sizes.length > 0) {
        const firstAvailableSize = firstColor.sizes.find(
          (size: any) => size.quantity > 0,
        );
        if (firstAvailableSize) {
          setSelectedSkuId(firstAvailableSize.sku_id);
        } else if (firstColor.sizes.length > 0) {
          setSelectedSkuId(firstColor.sizes[0].sku_id);
        }
      }
    }
  }, [colors, hasColors, selectedColor]);

  // Update selected SKU when color changes - select first available size of new color
  useEffect(() => {
    if (
      selectedColor &&
      selectedColor.sizes &&
      selectedColor.sizes.length > 0
    ) {
      const firstAvailableSize = selectedColor.sizes.find(
        (size) => size.quantity > 0,
      );
      if (firstAvailableSize) {
        setSelectedSkuId(firstAvailableSize.sku_id);
      } else if (selectedColor.sizes.length > 0) {
        setSelectedSkuId(selectedColor.sizes[0].sku_id);
      }
    } else {
      setSelectedSkuId(null);
    }
  }, [selectedColor]);

  const handleColorSelect = (color: Variant) => {
    setSelectedColor(color);
    setSelectedColorImage(color?.images?.[0]?.url || null);
    // console.log('^^^^^ clicked', color, product)
  };

  const handleSizeSelect = (skuId: string) => {
    setSelectedSkuId(skuId);
  };

  const handleAddToCart = async () => {
    // if (!selectedSkuId) return;

    try {
      if (product?.variants?.length > 0) {
        const res = await addItem(product._id, selectedSkuId, 1);
        toast.dismiss();
        toast.success(res.data?.message || "Item added to cart successfully");
        setAdded(true);

        setTimeout(() => {
          setAdded(false);
          onClose();
        }, 700);
      } else {
        setShowPopup?.(false);
        setShowLeadModal?.(true);
      }
    } catch (error) {
      console.error("Error adding to cart", error);
      toast.error("Failed to add item to cart");
    }
  };

  const handleNavigation = (product: any) => {
    router.push(`/productdetails/${product?.slug}`);
  };

  // Check if selected size is out of stock
  const isSelectedSizeOutOfStock = () => {
    if (!selectedColor || !selectedSkuId) return false;
    const selectedSize = selectedColor.sizes.find(
      (size) => size.sku_id === selectedSkuId,
    );
    return selectedSize ? selectedSize.quantity <= 0 : false;
  };

  // Check if there is no SKU data at all
  const hasNoSkuData =
    !hasColors && (!product.skus || product.skus.length === 0);

  const canAdd =
    selectedSkuId !== null &&
    !isSelectedSizeOutOfStock() &&
    (!hasColors || selectedColor !== null) &&
    !hasNoSkuData;

  return (
    <>
      {/* Backdrop */}
      {/* <div
        onClick={onClose}
        style={{
          position: "fixed",
          inset: 0,
          zIndex: 8,
          backgroundColor: "rgba(0, 0, 0, 0.50)"
        }}
      /> */}

      {/* Popup */}
      <div
        ref={popupRef}
        className="absolute bottom-[10px] left-1 right-1 z-[9] w-[auto] animate-[quickPopupFade_0.2s_ease] bg-[#FFFBF2] p-2 shadow-[0_5px_20px_rgba(0,0,0,0.15)] sm:left-2 sm:right-auto sm:w-[185px] sm:p-3 md:w-[185px] xl:w-[220px] 2xl:w-[320px] 2xl:p-4"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Arrow */}
        {/* <div className="absolute -bottom-[7px] sm:-bottom-2 right-[18px] w-3 h-3 sm:w-4 sm:h-4 bg-white rotate-45 border-r border-b border-[#ececec]" /> */}

        {/* Header */}
        <div className="mb-1 flex items-start justify-between sm:mb-1">
          <div className="flex w-full flex-col items-center gap-[5px] sm:gap-[10px]">
            <img
              src={selectedColorImage || product.image}
              alt={product.name}
              className="h-[60px] w-full rounded-[0px] border-0 object-cover object-top sm:h-[110px] 2xl:h-[160px]"
            />

            <div className="flex w-full min-w-[0px] flex-grow justify-between gap-2">
              <p className="m-0 line-clamp-1 text-left text-[13px] font-medium text-[#E1A472] sm:text-[14px] 2xl:text-[20px]">
                {product.name.length > 24
                  ? product.name.substring(0, 24) + "..."
                  : product.name}
              </p>

              <div className="flex justify-end items-end flex-col">
                <span className="text-[13px] font-semibold leading-[100%] text-[#201E1C] sm:text-[14px] 2xl:text-[20px]">
                  ₹{product.price?.toLocaleString("en-IN")}
                </span>

                {product.price < product.originalPrice && (
                  <span className="text-[10px] text-[#ACACAC] line-through sm:text-[12px] 2xl:text-[18px]">
                    ₹{product.originalPrice?.toLocaleString("en-IN")}
                  </span>
                )}
              </div>
            </div>
          </div>

          {/* <button
            onClick={onClose}
            style={{
              background: "transparent",
              border: "none",
              cursor: "pointer",
              padding: 0,
              display: "flex",
            }}
          >
            <X size={18} color="#999" />
          </button> */}
        </div>

        {/* Color */}
        {hasColors && (
          <div className="mb-1 sm:mb-2">
            <p className="mb-1 mt-0 text-left text-[10px] font-normal text-[#201E1C] [font-family:var(--font-heading)] sm:mb-1 sm:text-base 2xl:text-xl">
              Select Color :
            </p>

            <div className="flex items-center gap-1">
              {visibleColors.map((color) => {
                const isSelected = selectedColor?._id === color._id;

                return (
                  <button
                    key={color._id}
                    onClick={() => handleColorSelect(color)}
                    title={color.name}
                    className={`relative flex h-5 w-5 items-center justify-center drop-shadow-[0px_0px_1px_rgba(0,0,0,0.10)] transition-all duration-200 md:h-7 md:w-7 xl:h-8 xl:w-8 2xl:h-9 2xl:w-9 ${isSelected ? "" : ""} `}
                    style={{
                      backgroundColor: color.hexCode,
                      border: isSelected ? "" : "",
                      boxShadow: isSelected
                        ? `#ddd 0px 0px 0px 1px inset, #fff 0px 0px 0px 2px inset`
                        : "none",
                    }}
                  >
                    {isSelected && (
                      <Check
                        size={12}
                        color={
                          color.hexCode?.toLowerCase() === "#ffffff"
                            ? "#000"
                            : "#fff"
                        }
                      />
                    )}
                  </button>
                );
              })}

              {remainingColors > 0 && (
                <Tooltip text="See More">
                  <span
                    className="inline-flex h-5 w-5 cursor-pointer items-center justify-center border border-[#8E8E8E] text-xs font-medium text-gray-500 md:h-7 md:w-7 xl:h-8 xl:w-8 xl:text-base 2xl:h-9 2xl:w-9"
                    onClick={() => handleNavigation(product)}
                  >
                    {/* +{remainingColors} */}
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      className="2x:h-[24px] h-[22px] w-[22px] 2xl:w-[24px]"
                      fill="currentColor"
                      viewBox="0 0 16 16"
                    >
                      <path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3m5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3m5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3" />
                    </svg>
                  </span>
                </Tooltip>
              )}
            </div>
          </div>
        )}

        {/* Sizes */}
        {availableSizes?.length > 0 && (
          <div className="mb-[10px] sm:mb-[18px]">
            <p className="mb-1 mt-0 text-left text-[10px] font-normal text-[#201E1C] [font-family:var(--font-heading)] sm:mb-1 sm:text-base 2xl:text-xl">
              Select Size :
            </p>

            {hasNoSkuData ? (
              <p className="text-[10px] text-[#999] sm:text-xs 2xl:text-base">
                Out of Stock
              </p>
            ) : hasColors && !selectedColor ? (
              <p className="text-[10px] text-[#999] sm:text-xs 2xl:text-base">
                Please select a color first
              </p>
            ) : (
              <div className="flex flex-wrap items-center gap-1">
                {visibleSizes.map((size) => {
                  const isSelected = selectedSkuId === size.sku_id;
                  const outOfStock = size.quantity <= 0;

                  return (
                    <button
                      key={size.sku_id}
                      disabled={outOfStock}
                      onClick={() => handleSizeSelect(size.sku_id)}
                      className={`h-5 min-w-7 text-xs font-medium transition-all md:h-6 md:min-w-10 2xl:h-8 2xl:min-w-12 2xl:text-base ${
                        isSelected
                          ? "bg-[#DDA16B] text-white"
                          : "bg-white text-[#201E1C]"
                      } ${outOfStock ? "cursor-not-allowed opacity-40" : ""} `}
                    >
                      {size.name.toUpperCase()}
                    </button>
                  );
                })}

                {remainingSizes > 0 && (
                  <Tooltip text="See More">
                    <div
                      className="flex h-5 min-w-7 cursor-pointer items-center justify-center border border-gray-200 bg-white text-base text-xs font-medium text-[#8E8E8E] md:h-6 md:min-w-10 2xl:h-8 2xl:min-w-12 2xl:text-base"
                      onClick={() => handleNavigation(product)}
                    >
                      {/* +{remainingSizes} */}
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        className="2x:h-[24px] h-[22px] w-[22px] 2xl:w-[24px]"
                        fill="currentColor"
                        viewBox="0 0 16 16"
                      >
                        <path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3m5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3m5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3" />
                      </svg>
                    </div>
                  </Tooltip>
                )}
              </div>
            )}
          </div>
        )}

        {/* Add Button */}
        <button
          onClick={handleAddToCart}
          disabled={loading}
          className={`theme-btn flex !h-[30px] !min-h-[initial] w-full items-center justify-center !gap-1 gap-1 rounded-[0px] border-0 bg-[#dda16b] !px-[4px] !text-[10px] !font-medium !capitalize !tracking-normal text-white transition-all duration-200 sm:!h-[42px] sm:gap-2 sm:!px-[10px] sm:!text-[13px] md:!gap-2 2xl:!h-[48px] 2xl:!text-[16px] ${
            !loading ? "cursor-pointer" : "cursor-not-allowed"
          }`}
        >
          {added ? (
            <>
              <Check size={16} />
              Added to Cart
            </>
          ) : loading ? (
            "Adding..."
          ) : (
            <>
              <ShoppingBag size={16} />
              {product?.variants?.length > 0
                ? "Add to Cart"
                : "Proceed To Inquiry"}
            </>
          )}
        </button>

        <style jsx>{`
          @keyframes quickPopupFade {
            from {
              opacity: 0;
              transform: translateY(-100px);
            }
            to {
              opacity: 1;
              transform: translateY(0);
            }
          }
        `}</style>
      </div>
    </>
  );
}
