import * as React from 'react';
import { useContext } from 'react';
import { translate as _t } from '@assets/js-shop/ShopUtils';
import { ICartItem } from '@assets/js-shop/GraphQLInterfaces';
import { DataContext } from '@assets/js-shop/context';
import { CartItem } from '@assets/js-shop/cart/cartBody/CartItem';
import { Utils } from '@assets/js-shop/cart/Utils';

interface CartItemsListProps {
   lastAddedProduct: null | ICartItem;
   handleProductChange: (e: React.MouseEvent<HTMLButtonElement> | React.ChangeEvent, item: ICartItem, offset: number) => void;
}

export function CartboxList(props: CartItemsListProps) {
   const context = useContext(DataContext);

   return <div className="cartbox-product-list">
      {context.cart.items.length ?
         <div className="cartbox-productlist">
            {context.cart.items.map((item: ICartItem, i: number) => {
               const isLastAdded = props.lastAddedProduct && Utils.findProductInCart(context.cart.items, props.lastAddedProduct, false) === item;

               return <CartItem key={item.id ?? i} item={item} onChange={props.handleProductChange} isLastAdded={isLastAdded} />;
            })}
         </div>
         :
         <p className="no-items">{_t('zadneZbozi')}</p>
      }
   </div>;
}
