'use client';

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

interface AddToCartProps {
  product: ProductDetailData;
  selectedVariant: SelectedVariant;
  onAddToCart: (item: CartItem) => void;
  className?: string;
}

export function AddToCart({ 
  product, 
  selectedVariant, 
  onAddToCart, 
  className = '' 
}: AddToCartProps) {
  const [quantity, setQuantity] = useState(1);
  const [isAdding, setIsAdding] = useState(false);

  const { price, stock, variant } = selectedVariant;
  const isInStock = stock > 0;
  const maxQuantity = Math.min(stock, 10); // Limit to 10 or available stock

  const handleQuantityChange = (newQuantity: number) => {
    setQuantity(Math.max(1, Math.min(newQuantity, maxQuantity)));
  };

  const handleAddToCart = async () => {
    if (!isInStock || isAdding) return;

    setIsAdding(true);
    
    try {
      const cartItem: CartItem = {
        id: `${product.id}-${variant?.id || 'no-variant'}-${Date.now()}`,
        productId: product.id,
        variantId: variant?.id,
        name: product.name,
        price: price,
        quantity: quantity,
        image: product.images[0] || '/assets/placeholder.png',
        size: selectedVariant.size,
        color: selectedVariant.color,
        maxStock: stock
      };

      await onAddToCart(cartItem);
      
      // Success feedback could be added here
      console.log('Added to cart:', cartItem);
      
    } catch (error) {
      console.error('Failed to add to cart:', error);
      // Error handling could be added here
    } finally {
      setIsAdding(false);
    }
  };

  const isVariantSelected = () => {
    // Check if required variants are selected
    const hasSize = product.availableSizes.length === 0 || selectedVariant.size;
    const hasColor = product.availableColors.length === 0 || selectedVariant.color;
    return hasSize && hasColor;
  };

  const getButtonText = () => {
    if (!isVariantSelected()) {
      return 'Select Options';
    }
    if (!isInStock) {
      return 'Out of Stock';
    }
    if (isAdding) {
      return 'Adding...';
    }
    return 'Add to Cart';
  };

  const isButtonDisabled = () => {
    return !isVariantSelected() || !isInStock || isAdding;
  };

  return (
    <div className={`space-y-4 ${className}`}>
      {/* Price Display */}
      <div className="space-y-1">
        <div className="flex items-baseline space-x-2">
          <span className="text-3xl font-bold text-gray-900">
            {ProductDetailService.formatPrice(price)}
          </span>
          {variant && variant.price !== product.base_price && (
            <span className="text-lg text-gray-500 line-through">
              {ProductDetailService.formatPrice(product.base_price)}
            </span>
          )}
        </div>
        
        {product.priceRange.min !== product.priceRange.max && (
          <p className="text-sm text-gray-600">
            Price range: {ProductDetailService.formatPrice(product.priceRange.min)} - {ProductDetailService.formatPrice(product.priceRange.max)}
          </p>
        )}
      </div>

      {/* Quantity Selector */}
      {isInStock && isVariantSelected() && (
        <div className="space-y-2">
          <label htmlFor="quantity" className="block text-sm font-medium text-gray-700">
            Quantity
          </label>
          <div className="flex items-center space-x-3">
            <button
              type="button"
              onClick={() => handleQuantityChange(quantity - 1)}
              disabled={quantity <= 1}
              className="w-10 h-10 rounded-md border border-gray-300 flex items-center justify-center text-gray-600 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
            >
              <MinusIcon className="w-4 h-4" />
            </button>
            
            <input
              type="number"
              id="quantity"
              min="1"
              max={maxQuantity}
              value={quantity}
              onChange={(e) => handleQuantityChange(parseInt(e.target.value) || 1)}
              className="w-20 px-3 py-2 border border-gray-300 rounded-md text-center focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
            
            <button
              type="button"
              onClick={() => handleQuantityChange(quantity + 1)}
              disabled={quantity >= maxQuantity}
              className="w-10 h-10 rounded-md border border-gray-300 flex items-center justify-center text-gray-600 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
            >
              <PlusIcon className="w-4 h-4" />
            </button>
            
            <span className="text-sm text-gray-600">
              {stock} available
            </span>
          </div>
        </div>
      )}

      {/* Add to Cart Button */}
      <button
        onClick={handleAddToCart}
        disabled={isButtonDisabled()}
        className={`
          w-full py-3 px-8 rounded-md font-medium text-white transition-colors duration-200
          ${isButtonDisabled()
            ? 'bg-gray-300 cursor-not-allowed'
            : 'bg-blue-600 hover:bg-blue-700 active:bg-blue-800'
          }
        `}
      >
        {getButtonText()}
      </button>

      {/* Variant Selection Hints */}
      {!isVariantSelected() && (
        <div className="text-sm text-gray-600 space-y-1">
          {product.availableSizes.length > 0 && !selectedVariant.size && (
            <p>Please select a size</p>
          )}
          {product.availableColors.length > 0 && !selectedVariant.color && (
            <p>Please select a color</p>
          )}
        </div>
      )}

      {/* Stock Warning */}
      {isInStock && stock < 5 && isVariantSelected() && (
        <div className="bg-orange-50 border border-orange-200 rounded-md p-3">
          <p className="text-sm text-orange-800">
            <span className="font-medium">Limited stock:</span> Only {stock} left in stock
          </p>
        </div>
      )}

      {/* Product Details */}
      <div className="border-t pt-4 space-y-2 text-sm text-gray-600">
        <div className="flex justify-between">
          <span>Brand:</span>
          <span className="font-medium">{product.brand}</span>
        </div>
        {variant && (
          <div className="flex justify-between">
            <span>SKU:</span>
            <span className="font-medium">{variant.sku}</span>
          </div>
        )}
        <div className="flex justify-between">
          <span>Category:</span>
          <span className="font-medium">{product.category.name}</span>
        </div>
      </div>
    </div>
  );
}

// Simple icon components
const PlusIcon = ({ className }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
  </svg>
);

const MinusIcon = ({ className }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 12h-15" />
  </svg>
);