import { useEffect, useMemo, useRef, useState } from 'react'
import { OnChangeArgs, Product } from '../interfaces/Product';
import { InitialValues } from '../components/ProductCard';

interface Props {
  product: Product;
  onChange?: ({ product, count }: OnChangeArgs) => void;
  value?: number;
  initialValues?: InitialValues;
}

const useProduct = ({ product, onChange, value = 0, initialValues }: Props) => {
  const [counter, setCounter] = useState<number>(initialValues?.count || value);

  const isMounted = useRef(false)
  const isControlled = useRef(!!onChange)
  
  const isMaxCountReached = useMemo(() => !!initialValues?.maxCount && initialValues.maxCount === counter, [counter, initialValues])

  useEffect(() => {
    if (!isMounted.current) return
    value !== undefined && setCounter(value)
  }, [value])

  useEffect(() => {
    isMounted.current = true
  }, [])
  
  

  const handleIncreaseBy = (updated: number) => {
    if (isControlled && onChange) {
      onChange({ product, count: Math.max(value + updated, 0) })
      return
    }
    let newValue = Math.max(counter + updated, 0)
    if (!!initialValues?.maxCount) {
      newValue = Math.min(newValue, initialValues.maxCount)
    }
    setCounter(newValue);
  }

  const onReset = () => {
    setCounter(initialValues?.count || value)
  }

  return {
    counter,
    maxCount: initialValues?.maxCount,
    isMaxCountReached,
    handleIncreaseBy,
    onReset,
  }
}

export default useProduct