import * as React from 'react';
import { type MouseEvent, type SyntheticEvent, useContext, useEffect, useMemo, useState } from 'react';
import type { BuyCountProps } from './BuyCount';
import type { ProductChangeFunc } from '@assets/js-shop/cart/Cart';
import { DataContext } from '@assets/js-shop/context';
import { Utils } from '@assets/js-shop/cart/Utils';
import { translate as _t } from '@assets/js-shop/ShopUtils';

type ProductDetailCounterProps = {
   product: { productId: number, variationId: number | null };
   buyCount: BuyCountProps['buyCount'];
   updateCartProduct: ProductChangeFunc;
};

function useCartItem(product: ProductDetailCounterProps['product']) {
   const { cart } = useContext(DataContext);

   return useMemo(() => {
      return Utils.findProductInCart(cart?.items ?? [], product, false);
   }, [cart, product]);
}

export function ProductDetailCounter(props: ProductDetailCounterProps) {
   const { product, buyCount, updateCartProduct } = props;
   const { max, step, shortUnit } = buyCount;

   const item = useCartItem(product);
   const [pieces, setPieces] = useState(item?.pieces ?? 0);

   useEffect(() => {
      setPieces(item?.pieces ?? 0);
   }, [item?.pieces]);

   function submitCount(ev: SyntheticEvent<HTMLInputElement>) {
      const offset = pieces - (item?.pieces ?? 0);
      // nothing changed
      if (offset === 0) {
         return;
      }

      updateCartProduct(ev as MouseEvent<HTMLInputElement>, item ?? product, offset);
   }

   function increment(ev: MouseEvent<HTMLButtonElement>) {
      if (ev.currentTarget.disabled || (!!max && (pieces + max) > max)) {
         return;
      }

      updateCartProduct(ev, item ?? product, +step);
   }

   function decrement(ev: MouseEvent<HTMLButtonElement>) {
      if (ev.currentTarget.disabled || (pieces - step) < 0) {
         return;
      }

      updateCartProduct(ev, item, -step);
   }

   return (
      <>
         <input
            className="form-control"
            type="number"
            name="No"
            title="Počet ks"
            onBlur={submitCount}
            onKeyDown={ev => void (ev.key === 'Enter' && submitCount(ev))}
            onChange={ev => {
               const maybeValue = ev.currentTarget.value.trim();
               if (isNaN(+maybeValue)) {
                  setPieces(0);
                  return;
               }

               setPieces(+maybeValue);
            }}
            value={pieces || ''}
            placeholder="0"
         />
         <div>
            <button
               type="button"
               className="plus_unit"
               title={`${_t('pridat')} ${step} ${shortUnit}`}
               onClick={increment}
               disabled={!!max && pieces >= max}
            >
               <i className="c-icon" dangerouslySetInnerHTML={{ __html: MODULES.COMPONENTS ? require('@assets/icons/caret-up.svg?raw'): '' }} />
            </button>
            <button
               type="button"
               className="minus_unit"
               title={`${_t('odebrat')} ${step} ${shortUnit}`}
               onClick={decrement}
               disabled={pieces <= 0}
            >
               <i className="c-icon" dangerouslySetInnerHTML={{ __html: MODULES.COMPONENTS ? require('@assets/icons/caret-down.svg?raw'): ''  }} />
            </button>
         </div>
      </>
   );
}
