'use client';

import { Button } from "@/components/ui/Button";
import { useTranslation } from "@/lib/hooks/useTranslation";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import { clearBox, selectBoxItems } from "@/lib/redux/slices/boxSlice";
import { addItem } from "components/cart/actions";
import { useCart } from "components/cart/cart-context";
import { useRouter } from "next/navigation";
import { useState } from "react";

interface AddBoxToCartClientWithTranslationProps {
  buttonText?: string;
}

export function AddBoxToCartClientWithTranslation({ buttonText }: AddBoxToCartClientWithTranslationProps) {
  const { t } = useTranslation();
  const [isLoading, setIsLoading] = useState(false);
  const dispatch = useAppDispatch();
  const boxItems = useAppSelector(selectBoxItems);
  const router = useRouter();
  const { addCartItem } = useCart();
  
  // Check if we have a box container
  const hasBoxContainer = boxItems.some(item => item.variantId === 'box-container');
  
  // Disable the button if no box container is selected
  const isDisabled = !hasBoxContainer;
  
  const handleAddToCart = async () => {
    setIsLoading(true);
    
    try {
      // Get box container details (for image, name etc.)
      const boxContainer = boxItems.find(item => item.variantId === 'box-container');
      
      if (!boxContainer) {
        throw new Error('No box container selected');
      }
      
      // Generate a unique box ID to group all items together
      const boxGroupId = `box-${Date.now()}`;
      
      // Add box to cart with attribute marking it as a box container
      await addItem(
        null, 
        boxContainer.id, 
        1,
        [
          { key: "_box_type", value: "container" },
          { key: "_box_group_id", value: boxGroupId }
        ]
      );
      
      // Add all product items with same box group ID
      for (const item of boxItems.filter(i => i.variantId !== 'box-container')) {
        await addItem(
          null,
          item.id,
          item.quantity,
          [
            { key: "_box_type", value: "item" },
            { key: "_box_group_id", value: boxGroupId }
          ]
        );
      }
      
      // Clear the box
      dispatch(clearBox());
      
      // Redirect to cart page
      router.push('/cart');
    } catch (error) {
      console.error('Error adding box to cart:', error);
    } finally {
      setIsLoading(false);
    }
  };
  
  return (
    <Button 
      variant="primary"
      onClick={handleAddToCart}
      className="w-full py-3"
      disabled={isDisabled || isLoading}
    >
      {isLoading ? 'Loading...' : (buttonText || t('buildBox.customize.addToCart'))}
    </Button>
  );
} 