import * as React from 'react';
import { SelectionItem } from '@assets/js-multisets/sidebar/selection-row/SelectionItem';
import type {
   SidebarToggleFunc,
   Product,
   Selection,
} from '@assets/js-multisets/common/types';
import type { ResultOf } from '@graphql-typed-document-node/core';
import type { MULTI_SET_CATEGORY_FIELDS } from '@assets/js-multisets/common/constants/query';
import { ItemNavigation } from '@assets/js-multisets/item-navigation/ItemNavigation';

type SelectionRowProps = {
   data: ResultOf<typeof MULTI_SET_CATEGORY_FIELDS>;
   row: number;
   selection: Record<number, Selection>;
   onSidebarToggle: SidebarToggleFunc;
   activeProduct: Product;
   activeFocusVariation?: number;
}

export function SelectionRow(props: SelectionRowProps) {
   const { data: { products, id }, row, activeProduct, onSidebarToggle, activeFocusVariation } = props;
   let nextActivate = false;

   return (
      <div className="jsmultisets-selection-row">
         <ItemNavigation numberOfDisplayedItems={2} moveBy={1}>
            {products.map(product => {
               if ((product.inStore === 0) && (activeProduct.id == product.id)) {
                  nextActivate = true;
               } else if (product.inStore !== 0) {
                  if (nextActivate) {
                     nextActivate = false;
                     onSidebarToggle(null, {...product, row : row}, row, id);
                  }
               }

               if (product.inStore > 0) {
                  return <SelectionItem
                     key={product.id}
                     data={product}
                     categoryId={id}
                     row={row}
                     isChecked={activeProduct.id == product.id}
                     onSidebarToggle={onSidebarToggle}
                     activeFocusVariation={activeProduct.id == product.id && activeFocusVariation}
                  />
               }
            })}
         </ItemNavigation>
      </div>
   );
}
