"use client";

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

type ColorType = {
    _id: string,
    name: string,
    hexCode: string
}

type Sku = {
  _id: string;
  sku: string;
  color: ColorType | null;
  size: { _id: string; name: string } | null;
  price: { $numberDecimal: string } | number;
  comparePrice: { $numberDecimal: string } | number;
  quantity: number;
};

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 = {
  isOpen: boolean;
  onClose: () => void;
  product: {
    _id: string;
    name: string;
    image: string;
    price: number;
    originalPrice: number;
    skus: Sku[];
    variants: Variant[]
    totalQuantity: number
  };
};

export default function SkuSelectorModal({ isOpen, onClose, product }: Props) {
  const { addItem, loading } = useCart();
  const [selectedColor, setSelectedColor] = useState<Variant | null>(null);
  const [selectedSkuId, setSelectedSkuId] = useState<string | null>(null);
  const [added, setAdded] = useState(false);
//   console.log('P ^^^^^^^', product)

  const outOfStock = product?.totalQuantity <= 0
  const colors: Variant[] = product?.variants || []

  const hasColors = colors.length > 0;

  // Get available sizes — filtered by selected color if colors exist
  const availableSizes = selectedColor?.sizes || [];

  // Reset on open
  useEffect(() => {
    if (isOpen) {
      setSelectedColor(hasColors ? null : null);
      setSelectedSkuId(null);
      setAdded(false);
    }
  }, [isOpen]);

  // 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(prev => prev === skuId ? null : skuId);
  };

  const handleAddToCart = async () => {
    if (!selectedSkuId) return;
    try {
        await addItem(product._id, selectedSkuId, 1);
        
        setAdded(true);
        setAdded(false);
        onClose();
    } catch(error) {
        console.error('Error add to cart', error)
    }
  };

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

  if (!isOpen) return null;

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

      {/* Modal */}
      <div style={{
        position: "fixed",
        bottom: 0, left: 0, right: 0,
        background: "#fff",
        borderRadius: "20px 20px 0 0",
        padding: "24px",
        zIndex: 9999,
        maxHeight: "90vh",
        overflowY: "auto",
        boxShadow: "0 -4px 20px rgba(0,0,0,0.15)",
      }}>
        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: "20px" }}>
          <div style={{ display: "flex", gap: "12px", alignItems: "center" }}>
            <img
              src={product.image}
              alt={product.name}
              style={{ width: 60, height: 60, objectFit: "cover", borderRadius: 8 }}
            />
            <div>
              <p style={{ margin: 0, fontSize: 15, fontWeight: 500, color: "#30232a", maxWidth: 220 }}>{product.name}</p>
              <div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 4 }}>
                <span style={{ fontSize: 16, fontWeight: 600, color: "#30232a" }}>
                  ₹{product.price?.toLocaleString("en-IN")}
                </span>
                <span style={{ fontSize: 13, color: "#898989", textDecoration: "line-through" }}>
                  ₹{product.originalPrice?.toLocaleString("en-IN")}
                </span>
              </div>
            </div>
          </div>
          <button
            onClick={onClose}
            style={{ background: "none", border: "none", cursor: "pointer", padding: 4 }}
          >
            <X size={22} color="#30232a" />
          </button>
        </div>

        {/* Color Selection */}
        {hasColors && (
          <div style={{ marginBottom: 20 }}>
            <p style={{ margin: "0 0 10px", fontSize: 14, fontWeight: 500, color: "#30232a" }}>
              Color {selectedColor && <span style={{ color: "#898989", fontWeight: 400 }}>— {selectedColor.name}</span>}
            </p>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
              {colors.map((color) => {
                const isSelected = selectedColor?._id === color._id;

                return (
                    <button
                    key={color._id}
                    onClick={() => handleColorSelect(color)}
                    style={{
                        padding: "6px 16px",
                        borderRadius: "999px",
                        border: isSelected ? "2px solid #dda16b" : "1.5px solid #ddd",
                        background: isSelected ? "rgba(221,161,107,0.08)" : "#fff",
                        color: isSelected ? "#8a5e2a" : "#30232a",
                        fontSize: 13,
                        fontWeight: isSelected ? 500 : 400,
                        cursor: "pointer",
                        transition: "all 0.15s",
                    }}
                    >
                        {color.name}
                    </button>
                );
                })}
            </div>
          </div>
        )}

        {/* Size Selection */}
        <div style={{ marginBottom: 24 }}>
          <p style={{ margin: "0 0 10px", fontSize: 14, fontWeight: 500, color: "#30232a" }}>
            Size
            {(!hasColors || selectedColor) && availableSizes?.length === 0 && (
              <span style={{ color: "#e53e3e", fontWeight: 400 }}> — No sizes available</span>
            )}
          </p>

          {hasColors && !selectedColor ? (
            <p style={{ fontSize: 13, color: "#898989" }}>Please select a color first</p>
          ) : (
            <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
              {availableSizes.map((size) => {
                const isSelected = selectedSkuId === size.sku_id;

                return (
                    <button
                    key={size.sku_id}
                    onClick={() => handleSizeSelect(size.sku_id)}
                    style={{
                        width: 46, height: 46,
                        borderRadius: 8,
                        border: isSelected ? "2px solid #dda16b" : "1.5px solid #ddd",
                        background: isSelected ? "#dda16b" : "#fff",
                        color: isSelected ? "#fff" : outOfStock ? "#bbb" : "#30232a",
                        fontSize: 13,
                        fontWeight: isSelected ? 500 : 400,
                        cursor: outOfStock ? "not-allowed" : "pointer",
                        opacity: outOfStock ? 0.4 : 1,
                        textDecoration: outOfStock ? "line-through" : "none",
                        transition: "all 0.15s",
                    }}
                    >
                        {size.name}
                    </button>
                );
                })}
            </div>
          )}
        </div>

        {/* Add to Cart Button */}
        <button
          onClick={handleAddToCart}
          disabled={!canAdd || loading}
          style={{
            width: "100%",
            padding: "14px",
            background: canAdd ? "rgba(221,161,107,1)" : "#ddd",
            color: canAdd ? "#fff" : "#999",
            border: "none",
            borderRadius: 8,
            fontSize: 15,
            fontWeight: 600,
            letterSpacing: 1,
            textTransform: "uppercase",
            cursor: canAdd ? "pointer" : "not-allowed",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: 8,
            transition: "all 0.2s",
          }}
        >
          {added ? (
            <><Check size={18} /> Added to Cart</>
          ) : loading ? (
            "Adding..."
          ) : (
            <><ShoppingBag size={18} /> Add to Cart</>
          )}
        </button>
      </div>
    </>
  );
}