'use client';

import React from 'react';
import { ProductDetailData, SelectedVariant } from '@/types/api';
import { ProductDetailService } from '@/services/productDetailService';

interface VariantSelectorProps {
  product: ProductDetailData;
  selectedVariant: SelectedVariant;
  onVariantChange: (size?: string, color?: string) => void;
  className?: string;
}

export function VariantSelector({ 
  product, 
  selectedVariant, 
  onVariantChange, 
  className = '' 
}: VariantSelectorProps) {
  const { availableSizes, availableColors, variants } = product;
  const { size: selectedSize, color: selectedColor } = selectedVariant;

  // Get available options based on current selection
  const availableColorsForSize = selectedSize 
    ? ProductDetailService.getAvailableColorsForSize(variants, selectedSize)
    : availableColors;
  
  const availableSizesForColor = selectedColor
    ? ProductDetailService.getAvailableSizesForColor(variants, selectedColor)
    : availableSizes;

  const handleSizeChange = (size: string) => {
    // If selecting a size that doesn't have the current color, clear the color
    const newColor = selectedColor && availableColorsForSize.includes(selectedColor) 
      ? selectedColor 
      : undefined;
    onVariantChange(size, newColor);
  };

  const handleColorChange = (color: string) => {
    // If selecting a color that doesn't have the current size, clear the size
    const newSize = selectedSize && availableSizesForColor.includes(selectedSize)
      ? selectedSize
      : undefined;
    onVariantChange(newSize, color);
  };

  const isVariantInStock = (checkSize?: string, checkColor?: string) => {
    return ProductDetailService.isVariantAvailable(variants, checkSize, checkColor);
  };

  return (
    <div className={`space-y-6 ${className}`}>
      {/* Size Selector */}
      {availableSizes.length > 0 && (
        <div>
          <h3 className="text-sm font-medium text-gray-900 mb-3">Size</h3>
          <div className="grid grid-cols-4 gap-2">
            {availableSizes.map((size) => {
              const isAvailable = availableSizesForColor.includes(size);
              const isSelected = selectedSize === size;
              const inStock = isVariantInStock(size, selectedColor);
              
              return (
                <button
                  key={size}
                  onClick={() => handleSizeChange(size)}
                  disabled={!isAvailable || !inStock}
                  className={`
                    relative py-3 px-4 text-sm font-medium border rounded-md transition-colors duration-200
                    ${isSelected
                      ? 'border-blue-600 bg-blue-50 text-blue-600'
                      : isAvailable && inStock
                      ? 'border-gray-300 bg-white text-gray-900 hover:border-gray-400'
                      : 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed'
                    }
                  `}
                >
                  {size}
                  {!inStock && (
                    <div className="absolute inset-0 flex items-center justify-center">
                      <div className="w-full h-0.5 bg-gray-400 transform rotate-45"></div>
                    </div>
                  )}
                </button>
              );
            })}
          </div>
          {selectedSize && (
            <p className="mt-2 text-sm text-gray-600">
              Selected size: <span className="font-medium">{selectedSize}</span>
            </p>
          )}
        </div>
      )}

      {/* Color Selector */}
      {availableColors.length > 0 && (
        <div>
          <h3 className="text-sm font-medium text-gray-900 mb-3">Color</h3>
          <div className="flex flex-wrap gap-3">
            {availableColors.map((color) => {
              const isAvailable = availableColorsForSize.includes(color);
              const isSelected = selectedColor === color;
              const inStock = isVariantInStock(selectedSize, color);
              
              return (
                <button
                  key={color}
                  onClick={() => handleColorChange(color)}
                  disabled={!isAvailable || !inStock}
                  className={`
                    relative group flex items-center space-x-2 py-2 px-4 border rounded-md transition-all duration-200
                    ${isSelected
                      ? 'border-blue-600 bg-blue-50 text-blue-600 shadow-sm'
                      : isAvailable && inStock
                      ? 'border-gray-300 bg-white text-gray-900 hover:border-gray-400 hover:shadow-sm'
                      : 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed'
                    }
                  `}
                >
                  {/* Color swatch */}
                  <div 
                    className={`
                      w-5 h-5 rounded-full border-2 shadow-sm
                      ${getColorClass(color)}
                      ${color.toLowerCase() === 'white' || color === '#FFFFFF' ? 'border-gray-400' : 'border-gray-300'}
                    `}
                    style={getColorStyle(color)}
                  />
                  <span className="text-sm font-medium">{getColorDisplayName(color)}</span>
                  
                  {!inStock && (
                    <div className="absolute inset-0 flex items-center justify-center">
                      <div className="w-full h-0.5 bg-gray-400 transform rotate-45"></div>
                    </div>
                  )}
                </button>
              );
            })}
          </div>
          {selectedColor && (
            <p className="mt-2 text-sm text-gray-600">
              Selected color: <span className="font-medium">{getColorDisplayName(selectedColor)}</span>
            </p>
          )}
        </div>
      )}

      {/* Variant Info */}
      {selectedVariant.variant && (
        <div className="bg-gray-50 rounded-lg p-4">
          <div className="flex justify-between items-center">
            <div>
              <p className="text-sm font-medium text-gray-900">
                SKU: {selectedVariant.variant.sku}
              </p>
              {(selectedSize || selectedColor) && (
                <p className="text-sm text-gray-600">
                  {[selectedSize, selectedColor].filter(Boolean).join(' • ')}
                </p>
              )}
            </div>
            <div className="text-right">
              <p className="text-lg font-bold text-gray-900">
                {ProductDetailService.formatPrice(selectedVariant.price)}
              </p>
              <StockStatus stock={selectedVariant.stock} />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// Helper component for stock status
function StockStatus({ stock }: { stock: number }) {
  const { status, color } = ProductDetailService.getStockStatus(stock);
  
  return (
    <p className={`text-sm font-medium ${color}`}>
      {status}
    </p>
  );
}

// Helper function to get color classes for common colors
function getColorClass(color: string): string {
  // If it's a hex color, don't apply any background class
  if (color.startsWith('#')) {
    return '';
  }
  
  const colorLower = color.toLowerCase();
  const colorMap: Record<string, string> = {
    black: 'bg-black',
    white: 'bg-white border-gray-400',
    red: 'bg-red-500',
    blue: 'bg-blue-500',
    green: 'bg-green-500',
    yellow: 'bg-yellow-500',
    purple: 'bg-purple-500',
    pink: 'bg-pink-500',
    orange: 'bg-orange-500',
    gray: 'bg-gray-500',
    grey: 'bg-gray-500',
    brown: 'bg-amber-700',
    beige: 'bg-amber-100',
    navy: 'bg-blue-900',
    maroon: 'bg-red-900',
  };
  
  return colorMap[colorLower] || '';
}

// Helper function to get inline styles for hex colors or non-standard color names
function getColorStyle(color: string): React.CSSProperties {
  // If it's a hex color (starts with #), use it directly
  if (color.startsWith('#')) {
    return { backgroundColor: color };
  }
  
  const colorLower = color.toLowerCase();
  const standardColors = ['black', 'white', 'red', 'blue', 'green', 'yellow', 'purple', 'pink', 'orange', 'gray', 'grey', 'brown', 'beige', 'navy', 'maroon'];
  
  // If it's a standard color, let Tailwind classes handle it
  if (standardColors.includes(colorLower)) {
    return {};
  }
  
  // For non-standard color names, try to use the color name as a CSS color
  return { backgroundColor: colorLower };
}

// Helper function to display color name or hex code
function getColorDisplayName(color: string): string {
  // If it's a hex color, display it as-is
  if (color.startsWith('#')) {
    return color.toUpperCase();
  }
  
  // Capitalize color names
  return color.charAt(0).toUpperCase() + color.slice(1);
}