import { useEffect, useState, useRef } from 'react';
import { InitialValues, Product, ProductCartOnChangeArgs } from '../interfaces';

interface UseProductProps {
  product: Product;
  onChange?: (arg: ProductCartOnChangeArgs) => void;
  value?: number;
  initialValues?: InitialValues
}

export const useProduct = ({ onChange, product, value = 0, initialValues }: UseProductProps) => {

  const [counter, setCounter] = useState<number>(initialValues?.count || value);
  const isMounted = useRef(false);

  const handleIncreseBy = (value: number) => {

    let newValue: number = Math.max(counter + value, 0);
    if (initialValues?.maxCount) {
      newValue = Math.min(newValue, initialValues.maxCount)
    }
    setCounter(newValue);
    onChange && onChange({ count: newValue, product });

  }

  const handleReset = () => {
    setCounter(initialValues?.count || value);
  }

  useEffect(() => {
    if (!isMounted.current) return;
    setCounter(value);
  }, [value])

  // useEffect(() => {
  //   // isMounted.current = true;
  // }, [])

  return {
    counter,
    isMaxCountReached: !!initialValues?.count && initialValues?.maxCount === counter,
    maxCount: initialValues?.maxCount,
    handleIncreseBy,
    handleReset
  }
}
