"use client";

import React, { useState, useEffect } from 'react';
import { useCart } from '@/hooks/useCart';
import { HeartIcon } from 'lucide-react';

interface ProductActionsProps {
  colors: any[];
  sizes: string[];
  variants: any[];
  productId: string;
  selectedColor?: any;
  onColorChange?: (color: any) => void;
}

export default function ProductActions({
  colors,
  sizes,
  variants,
  productId,
  selectedColor,
  onColorChange
}: ProductActionsProps) {
  const [selectedSize, setSelectedSize] = useState<any>(null);
  const [selectedSkuId, setSelectedSkuId] = useState<string | null>(null);
  const [quantity, setQuantity] = useState(1);
  const { addItem, loading } = useCart();

  // Find available sizes for selected color
  const getAvailableSizesForColor = () => {
    if (!selectedColor || !variants || variants.length === 0) return [];
    
    const variant = variants.find((v: any) => v._id === selectedColor.id);
    if (variant && variant.sizes) {
      return variant.sizes;
    }
    return [];
  };

  const availableSizes = getAvailableSizesForColor();
  
  // Auto-select first color if none selected and colors exist
  useEffect(() => {
    if (!selectedColor && colors && colors.length > 0 && onColorChange) {
      console.log("Auto-selecting first color:", colors[0]);
      onColorChange(colors[0]);
    }
  }, [colors, selectedColor, onColorChange]);

  // Reset size when color changes
  useEffect(() => {
    setSelectedSize(null);
    setSelectedSkuId(null);
  }, [selectedColor]);

  // Auto-select first size if available
  useEffect(() => {
    if (availableSizes.length > 0 && !selectedSize) {
      const firstSize = availableSizes[0];
      console.log("Auto-selecting first size:", firstSize);
      setSelectedSize(firstSize);
      setSelectedSkuId(firstSize.sku_id);
    }
  }, [availableSizes, selectedSize]);

  const handleColorSelect = (color: any) => {
    console.log("Color selected:", color);
    if (onColorChange) {
      onColorChange(color);
    }
  };

  const handleSizeSelect = (size: any) => {
    console.log("Size selected:", size);
    setSelectedSize(size);
    setSelectedSkuId(size.sku_id);
  };

  const handleQuantityChange = (type: 'increase' | 'decrease') => {
    if (type === 'increase') {
      setQuantity(prev => Math.min(prev + 1, 10));
    } else {
      setQuantity(prev => Math.max(prev - 1, 1));
    }
  };

  const handleAddToCart = async () => {
    if (!selectedSkuId) return;
    try {
      await addItem(productId, selectedSkuId, quantity);
      console.log("Added to cart:", { productId, selectedSkuId, quantity });
    } catch (error) {
      console.error('Error adding to cart:', error);
    }
  };

  return (
    <>
      {/* Color Selection */}
      {colors && colors.length > 0 && (
        <div className="mb-3 md:mb-5">
          <h3>Select Colour :</h3>
          <div className="filtercolor">
            {colors.map((color) => (
              <div className="radio" key={color.id}>
                <input
                  type="radio"
                  id={`color-${color.id}`}
                  name="color"
                  checked={selectedColor?.id === color.id}
                  onChange={() => handleColorSelect(color)}
                  style={{ display: 'none' }}
                />
                <label 
                  htmlFor={`color-${color.id}`}
                  style={{ 
                    background: color.code,
                    cursor: 'pointer',
                    border: selectedColor?.id === color.id ? '' : '',
                    boxShadow: selectedColor?.id === color.id ? 'inset 0px 0px 0px 2px #dda16b, inset 0px 0px 0px 4px #fff' : '',
                  }} 
                  title={color.name}
                />
              </div>
            ))}
          </div>
          {selectedColor && (
            <p className="text-sm text-gray-600 mt-2">Selected: {selectedColor.name}</p>
          )}
        </div>
      )}

      {/* Size Selection */}
      <div className="sizebxinner mb-3 md:mb-5">
        <h3>Select Sizes</h3>
        <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
          {availableSizes.length > 0 ? (
            availableSizes.map((size: any) => (
              <div className="radio size" key={size.sku_id}>
                <input
                  type="radio"
                  id={`size-${size.name}`}
                  name="size"
                  checked={selectedSize?.sku_id === size.sku_id}
                  onChange={() => handleSizeSelect(size)}
                  disabled={size.sku_quantity <= 0}
                  style={{ display: 'none' }}
                />
                <label 
                  htmlFor={`size-${size.name}`}
                  style={{
                    border: selectedSize?.sku_id === size.sku_id ? '' : '',
                    background: selectedSize?.sku_id === size.sku_id ? '#dda16b' : '#fff',
                    color: selectedSize?.sku_id === size.sku_id ? '#fff' : (size.sku_quantity <= 0 ? '#bbb' : '#30232a'),
                    cursor: size.sku_quantity <= 0 ? 'not-allowed' : 'pointer',
                    opacity: size.sku_quantity <= 0 ? 0.5 : 1,
                    transition: 'all 0.2s'
                  }}
                >
                  {size.name}
                  {size.sku_quantity <= 0 && <span className="stock-status"> (Out of Stock)</span>}
                </label>
              </div>
            ))
          ) : (
            <p className="text-gray-500 text-sm pt-1">
              {selectedColor ? 'No sizes available for this color' : 'Please select a color first'}
            </p>
          )}
        </div>
      </div>

      {/* Quantity and Add to Cart */}
      <div className="cartbtngroup md:max-w-[500px] 2xl:max-w-[700px]">
        <h3>Quantity</h3>
        <div className="flex gap-2 md:gap-2 lg:gap-4 mb-3">
          <div className="qtyinner">
            <button 
              type="button" 
              className="subbtns minusbtn" 
              onClick={() => handleQuantityChange('decrease')}
              style={{ cursor: 'pointer' }}
            >
              <i className="icon icon-minus"></i>
            </button>
            <input 
              type="text" 
              className="form-control" 
              value={quantity} 
              readOnly
            />
            <button 
              type="button" 
              className="plusbtn addbtns" 
              onClick={() => handleQuantityChange('increase')}
              style={{ cursor: 'pointer' }}
            >
              <i className="icon icon-plus"></i>
            </button>
          </div>
          
          <button 
            className="default-btn flex-grow hidden sm:flex !capitalize" 
            type="button"
            onClick={handleAddToCart}
            disabled={!selectedSkuId || loading}
            style={{
              cursor: selectedSkuId ? 'pointer' : 'not-allowed'
            }}
          >
            <svg viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M13.8857 18H3.85714C1.73571 18 0 16.2643 0 14.1429V14.0143L0.385714 3.72857C0.45 1.60714 2.18571 0 4.24286 0H13.5C15.5571 0 17.2929 1.60714 17.3571 3.72857L17.7429 14.0143C17.8071 15.0429 17.4214 16.0071 16.7143 16.7786C16.0071 17.55 15.0429 18 14.0143 18C14.0143 18 13.95 18 13.8857 18ZM4.24286 1.28571C2.82857 1.28571 1.73571 2.37857 1.67143 3.72857L1.28571 14.1429C1.28571 15.5571 2.44286 16.7143 3.85714 16.7143H14.0143C14.7214 16.7143 15.3643 16.3929 15.8143 15.8786C16.2643 15.3643 16.5214 14.7214 16.5214 14.0143L16.1357 3.72857C16.0714 2.31429 14.9786 1.28571 13.5643 1.28571H4.24286Z" fill="currentColor"/>
              <path d="M8.87143 7.71429C6.36429 7.71429 4.37143 5.72143 4.37143 3.21429C4.37143 2.82857 4.62857 2.57143 5.01429 2.57143C5.4 2.57143 5.65714 2.82857 5.65714 3.21429C5.65714 5.01429 7.07143 6.42857 8.87143 6.42857C10.6714 6.42857 12.0857 5.01429 12.0857 3.21429C12.0857 2.82857 12.3429 2.57143 12.7286 2.57143C13.1143 2.57143 13.3714 2.82857 13.3714 3.21429C13.3714 5.72143 11.3786 7.71429 8.87143 7.71429Z" fill="currentColor"/>
            </svg>
            <span>{loading ? 'Adding...' : 'Add To Cart'}</span>
          </button>
          
          <button className="wishlistbtn" type="button" style={{ cursor: 'pointer' }}>
            {/* <i className="fa-regular fa-heart"></i> */}
            <HeartIcon />
          </button>
        </div>
        
        <button 
          className="theme-btn w-full hidden sm:flex !capitalize" 
          type="button"
          disabled={!selectedSkuId}
          style={{
            cursor: selectedSkuId ? 'pointer' : 'not-allowed',
          }}
        >
          Buy Now
        </button>

        {/* Mobile Sticky Cart Button */}
        <div className="fixed left-0 right-0 bottom-0 flex sm:hidden sticky-cart-btn">
          <button 
            className="default-btn w-6/12 !capitalize" 
            type="button"
            onClick={handleAddToCart}
            disabled={!selectedSkuId || loading}
            style={{
              background: selectedSkuId ? '#dda16b' : '#ddd',
            }}
          >
            <svg viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M13.8857 18H3.85714C1.73571 18 0 16.2643 0 14.1429V14.0143L0.385714 3.72857C0.45 1.60714 2.18571 0 4.24286 0H13.5C15.5571 0 17.2929 1.60714 17.3571 3.72857L17.7429 14.0143C17.8071 15.0429 17.4214 16.0071 16.7143 16.7786C16.0071 17.55 15.0429 18 14.0143 18C14.0143 18 13.95 18 13.8857 18ZM4.24286 1.28571C2.82857 1.28571 1.73571 2.37857 1.67143 3.72857L1.28571 14.1429C1.28571 15.5571 2.44286 16.7143 3.85714 16.7143H14.0143C14.7214 16.7143 15.3643 16.3929 15.8143 15.8786C16.2643 15.3643 16.5214 14.7214 16.5214 14.0143L16.1357 3.72857C16.0714 2.31429 14.9786 1.28571 13.5643 1.28571H4.24286Z" fill="currentColor"/>
              <path d="M8.87143 7.71429C6.36429 7.71429 4.37143 5.72143 4.37143 3.21429C4.37143 2.82857 4.62857 2.57143 5.01429 2.57143C5.4 2.57143 5.65714 2.82857 5.65714 3.21429C5.65714 5.01429 7.07143 6.42857 8.87143 6.42857C10.6714 6.42857 12.0857 5.01429 12.0857 3.21429C12.0857 2.82857 12.3429 2.57143 12.7286 2.57143C13.1143 2.57143 13.3714 2.82857 13.3714 3.21429C13.3714 5.72143 11.3786 7.71429 8.87143 7.71429Z" fill="currentColor"/>
            </svg>
            <span>Add To Cart</span>
          </button>
          <button 
            className="theme-btn w-6/12 capitalize" 
            type="button"
            disabled={!selectedSkuId}
            style={{
              background: selectedSkuId ? '#30232a' : '#ddd',
            }}
          >
            Buy Now
          </button>
        </div>
      </div>
    </>
  );
}