"use client";

import { useState, useEffect, RefObject } from "react";
import { X, ShoppingBag, Check } from "lucide-react";
import { useCart } from "@/hooks/useCart";

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

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

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

  onClose: () => void;

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

  popupRef: RefObject<HTMLDivElement | null>;
};

export default function QuickAddPopup({
  product,
  onClose,
  position,
  popupRef,
}: Props) {
  const { addItem, loading } = useCart();

  const [selectedColor, setSelectedColor] = useState<Variant | null>(null);
  const [selectedSkuId, setSelectedSkuId] = useState<string | null>(null);
  const [added, setAdded] = useState(false);

  const colors: Variant[] = product?.variants || [];
  const hasColors = colors.length > 0;

  const availableSizes = selectedColor?.sizes || [];

  // Auto select first color and first available size on mount
  useEffect(() => {
    if (hasColors && colors.length > 0) {
      // Select first color
      const firstColor = colors[0];
      setSelectedColor(firstColor);
      
      // Select first available size (in stock) for the first color
      if (firstColor.sizes && firstColor.sizes.length > 0) {
        const firstAvailableSize = firstColor.sizes.find(size => size.quantity > 0);
        if (firstAvailableSize) {
          setSelectedSkuId(firstAvailableSize.sku_id);
        } else if (firstColor.sizes.length > 0) {
          // If no available sizes, select first size anyway (will be disabled)
          setSelectedSkuId(firstColor.sizes[0].sku_id);
        }
      }
    }
  }, [colors, hasColors]);

  // 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) {
        // If no available sizes, select first size anyway
        setSelectedSkuId(selectedColor.sizes[0].sku_id);
      }
    } else {
      setSelectedSkuId(null);
    }
  }, [selectedColor]);

  const handleColorSelect = (color: Variant) => {
    setSelectedColor(color);
  };

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

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

    try {
      await addItem(product._id, selectedSkuId, 1);
      setAdded(true);
      setTimeout(() => {
        setAdded(false);
        onClose();
      }, 700);
    } catch (error) {
      console.error("Error adding to cart", error);
    }
  };

  // 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;
  };

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

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

      {/* Popup */}
      <div
        ref={popupRef}
        className="absolute -right-1 sm:right-0 bottom-full w-[160px] sm:w-[270px] rounded-[14px] bg-white p-2 sm:p-4 z-[9] border border-[#ececec] shadow-[0_10px_30px_rgba(0,0,0,0.15)] animate-[quickPopupFade_0.2s_ease]"
        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="flex justify-between items-start mb-2 sm:mb-4">
          <div className="flex items-center gap-[5px] sm:gap-[10px]">
            <img
              src={product.image}
              alt={product.name}
              className="min-w-[40px] max-w-[40px] h-[40px] sm:min-w-[50px] sm:max-w-[50px] sm:h-[50px] rounded-lg object-cover border border-[#eee]"
            />

            <div className="text-left">
              <p className="m-0 text-[11px] sm:text-[13px] font-semibold text-[#222]">
                {product.name.length > 24
                  ? product.name.substring(0, 24) + "..."
                  : product.name}
              </p>

              <div className="flex items-center gap-1 sm:gap-1.5 mt-1">
                <span className="text-[11px] sm:text-[13px] text-[#dda16b]">
                  ₹{product.price?.toLocaleString("en-IN")}
                </span>

                {product.price < product.originalPrice && <span className="text-[10px] sm:text-[11px] line-through text-[#999]">
                  ₹{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 sm:mb-2 text-left text-[10px] sm:text-xs font-semibold text-[#666]">
              Select Color
            </p>

            <div className="flex flex-wrap gap-1 sm:gap-2">
              {colors.map((color) => {
                const isSelected = selectedColor?._id === color._id;

                return (
                  <button
                    key={color._id}
                    onClick={() => handleColorSelect(color)}
                    className="px-2 py-0.5 sm:px-3 sm:py-1.5 rounded-full text-[11px] sm:text-xs"
                    style={{
                      border: isSelected
                        ? "1.5px solid #dda16b"
                        : "1px solid #ddd",
                      background: isSelected
                        ? "rgba(221,161,107,0.12)"
                        : "#fff",
                      color: isSelected
                        ? "#8a5e2a"
                        : "#333",
                      fontWeight: isSelected ? 600 : 500,
                      cursor: "pointer",
                    }}
                  >
                    {color.name}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {/* Sizes */}
        <div className="mb-[10px] sm:mb-[18px]">
          <p className="mt-0 mb-1 sm:mb-2 text-left text-[10px] sm:text-xs font-semibold text-[#666]">
            Select Size
          </p>

          {hasColors && !selectedColor ? (
            <p className="text-[10px] sm:text-xs text-[#999]">
              Please select a color first
            </p>
          ) : (
            <div className="flex flex-wrap gap-1 sm:gap-2">
              {availableSizes.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="min-w-[30px] h-[24px] px-[5px] sm:min-w-[42px] sm:h-[34px] sm:px-[10px] rounded-lg text-[10px] sm:text-xs"
                    style={{
                      border: isSelected
                        ? "1.5px solid #dda16b"
                        : outOfStock
                        ? "1px solid #eee"
                        : "1px solid #ddd",
                      background: isSelected
                        ? "#dda16b"
                        : outOfStock
                        ? "#f5f5f5"
                        : "#fff",
                      color: isSelected
                        ? "#fff"
                        : outOfStock
                        ? "#ccc"
                        : "#333",
                      opacity: outOfStock ? 0.5 : 1,
                      cursor: outOfStock
                        ? "not-allowed"
                        : "pointer",
                      fontWeight: isSelected ? 600 : 500,
                    }}
                  >
                    {size.name}
                  </button>
                );
              })}
            </div>
          )}
        </div>

        {/* Add Button */}
        <button
          onClick={handleAddToCart}
          disabled={!canAdd || loading}
          className={`
            w-full h-[33px] sm:h-[42px] rounded-[10px] border-0
            font-bold text-[10px] sm:text-[13px]
            flex items-center justify-center gap-2
            transition-all duration-200
            ${
              canAdd
                ? "bg-[#dda16b] text-white"
                : "bg-[#ddd] text-[#888]"
            }
            ${
              canAdd && !loading
                ? "cursor-pointer"
                : "cursor-not-allowed"
            }
          `}
        >
          {added ? (
            <>
              <Check size={16} />
              Added to Cart
            </>
          ) : loading ? (
            "Adding..."
          ) : isSelectedSizeOutOfStock() ? (
            "Out of Stock"
          ) : (
            <>
              <ShoppingBag size={16} />
              Add to Cart
            </>
          )}
        </button>

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