import { useEffect, useRef, useState } from "react"
import { onChangeArgs, Product, InitialValues } from '../interfaces/product.interface';

interface Props {
    product: Product
    onChange?: (args: onChangeArgs) => void
    value?: number,
    initialValues?: InitialValues
}

export const useProduct = ({ onChange, product, value = 0, initialValues }: Props) => {
    const [count, setCount] = useState(initialValues?.count || value)
    const isMounted = useRef(false)

    const isControlled = useRef(!!onChange)

    const increaseBy = (value: number) => {

        let newValue = Math.max(count + value, 0)

        if (initialValues?.maxCount) {
            newValue = Math.min(newValue, initialValues.maxCount)
        }

        if (isControlled.current) {
            return onChange!({ count: value, product })
        }

        setCount(newValue)

        if (onChange) {
            onChange({
                count: newValue,
                product
            })
        }
    }

    const reset = () => {
        setCount(initialValues?.count || value)
    }

    useEffect(() => {
        if(!isMounted.current) return
        setCount(value)
    }, [value])

    useEffect(()=> {
        isMounted.current = true
    }, [])

    return {
        count,
        increaseBy,
        isMaxCountReached: !!initialValues?.count && initialValues.maxCount === count,
        maxCount: initialValues?.maxCount,
        reset
    }
}