"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 color if only one
  useEffect(() => {
    if (hasColors && colors.length === 1) {
      setSelectedColor(colors[0]);
    }
  }, [colors, hasColors]);

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

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

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

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

      {/* Popup */}
      <div
        ref={popupRef}
        style={{
          position: "absolute",
          // top: position.top,
          // left: position.left,
          right: "0px",
          top: "auto",
          bottom: "100%",
          transform: "translateY(0)",
          width: "260px",
          background: "#fff",
          borderRadius: "14px",
          padding: "16px",
          zIndex: 9999,
          boxShadow: "0 10px 30px rgba(0,0,0,0.15)",
          border: "1px solid #ececec",
          animation: "quickPopupFade 0.2s ease",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Arrow */}
        <div
          style={{
            position: "absolute",
            bottom: -8,
            right: 18,
            width: 16,
            height: 16,
            background: "#fff",
            transform: "rotate(45deg)",
            borderRight: "1px solid #ececec",
            borderBottom: "1px solid #ececec",
          }}
        />

        {/* Header */}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-start",
            marginBottom: 16,
          }}
        >
          <div
            style={{
              display: "flex",
              gap: 10,
              alignItems: "center",
            }}
          >
            <img
              src={product.image}
              alt={product.name}
              style={{
                width: 50,
                height: 50,
                borderRadius: 8,
                objectFit: "cover",
                border: "1px solid #eee",
              }}
            />

            <div>
              <p
                style={{
                  margin: 0,
                  fontSize: 13,
                  fontWeight: 600,
                  color: "#222",
                }}
              >
                {product.name.length > 24
                  ? product.name.substring(0, 24) + "..."
                  : product.name}
              </p>

              <div
                style={{
                  display: "flex",
                  gap: 6,
                  alignItems: "center",
                  marginTop: 4,
                }}
              >
                <span
                  style={{
                    fontSize: 13,
                    fontWeight: 700,
                    color: "#dda16b",
                  }}
                >
                  ₹{product.price?.toLocaleString("en-IN")}
                </span>

                <span
                  style={{
                    fontSize: 11,
                    textDecoration: "line-through",
                    color: "#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 style={{ marginBottom: 14 }}>
            <p
              style={{
                margin: "0 0 8px",
                fontSize: 12,
                fontWeight: 600,
                color: "#666",
              }}
            >
              Select Color
            </p>

            <div
              style={{
                display: "flex",
                flexWrap: "wrap",
                gap: 8,
              }}
            >
              {colors.map((color) => {
                const isSelected =
                  selectedColor?._id === color._id;

                return (
                  <button
                    key={color._id}
                    onClick={() => handleColorSelect(color)}
                    style={{
                      padding: "6px 12px",
                      borderRadius: 30,
                      border: isSelected
                        ? "1.5px solid #dda16b"
                        : "1px solid #ddd",
                      background: isSelected
                        ? "rgba(221,161,107,0.12)"
                        : "#fff",
                      color: isSelected
                        ? "#8a5e2a"
                        : "#333",
                      fontSize: 12,
                      fontWeight: isSelected ? 600 : 500,
                      cursor: "pointer",
                    }}
                  >
                    {color.name}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {/* Sizes */}
        <div style={{ marginBottom: 18 }}>
          <p
            style={{
              margin: "0 0 8px",
              fontSize: 12,
              fontWeight: 600,
              color: "#666",
            }}
          >
            Select Size
          </p>

          {hasColors && !selectedColor ? (
            <p
              style={{
                margin: 0,
                fontSize: 12,
                color: "#999",
              }}
            >
              Please select a color first
            </p>
          ) : (
            <div
              style={{
                display: "flex",
                flexWrap: "wrap",
                gap: 8,
              }}
            >
              {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)
                    }
                    style={{
                      minWidth: 42,
                      height: 34,
                      padding: "0 10px",
                      borderRadius: 8,
                      border: isSelected
                        ? "1.5px solid #dda16b"
                        : "1px solid #ddd",
                      background: isSelected
                        ? "#dda16b"
                        : "#fff",
                      color: isSelected ? "#fff" : "#333",
                      opacity: outOfStock ? 0.5 : 1,
                      cursor: outOfStock
                        ? "not-allowed"
                        : "pointer",
                      fontSize: 12,
                      fontWeight: 600,
                    }}
                  >
                    {size.name}
                  </button>
                );
              })}
            </div>
          )}
        </div>

        {/* Add Button */}
        <button
          onClick={handleAddToCart}
          disabled={!canAdd || loading}
          style={{
            width: "100%",
            height: 42,
            borderRadius: 10,
            border: "none",
            background: canAdd ? "#dda16b" : "#ddd",
            color: canAdd ? "#fff" : "#888",
            fontWeight: 700,
            fontSize: 13,
            cursor:
              canAdd && !loading
                ? "pointer"
                : "not-allowed",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 8,
            transition: "0.2s",
          }}
        >
          {added ? (
            <>
              <Check size={16} />
              Added to Cart
            </>
          ) : loading ? (
            "Adding..."
          ) : (
            <>
              <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>
    </>
  );
}