'use client';

import { useTranslation } from "@/lib/hooks/useTranslation";
import { addItem } from "components/cart/actions";
import { useCart } from "components/cart/cart-context";
import { Product, ProductVariant } from "lib/shopify/types";
import { useState } from "react";
import { Button } from "./Button";

interface AddToCartButtonProps {
  product: Product;
  className?: string;
  variantId?: string;
}

export function AddToCartButton({ product, className = "", variantId }: AddToCartButtonProps) {
  const [isLoading, setIsLoading] = useState(false);
  const { addCartItem } = useCart();
  const { t } = useTranslation();

  const handleAddToCart = async () => {
    if (isLoading) return;
    
    setIsLoading(true);
    
    // Get the selected variant or default to the first variant
    let selectedVariant: ProductVariant | undefined;
    
    if (variantId) {
      selectedVariant = product.variants.find(v => v.id === variantId);
    }
    
    // If no specified variant or variant not found, use the first one
    if (!selectedVariant) {
      selectedVariant = product.variants[0];
    }
    
    if (!selectedVariant || !selectedVariant.id) {
      setIsLoading(false);
      return;
    }
    
    try {
      // Add to backend cart
      await addItem(null, selectedVariant.id, 1);
      
      // Update local cart state
      addCartItem(selectedVariant, product, 1);
      
      // Set success message or notification here if needed
    } catch (error) {
      console.error("Failed to add item to cart:", error);
      // Handle error (could show error message)
    } finally {
      setTimeout(() => {
        setIsLoading(false);
      }, 500);
    }
  };

  return (
    <Button
      onClick={handleAddToCart}
      disabled={isLoading || !product.availableForSale}
      variant="primary"
      size="lg"
      className={`w-full ${className}`}
    >
      {isLoading 
        ? t('product.adding')
        : !product.availableForSale 
          ? t('product.outOfStock') 
          : t('product.addToCart')
      }
    </Button>
  );
} 