import React, { createContext } from "react";
import { useProduct } from '../hooks/useProduct';
import styles from "../styles/styles.module.css";
import { InitialValues, onChangeArgs, Product, ProductCardHandlers, ProductContextProps } from "../interfaces/interfaces";

export interface Props {
    product: Product;
    children: ( args: ProductCardHandlers ) => JSX.Element,
    value?: number;
    initialValues?: InitialValues;
    className?: string;
    style?: React.CSSProperties;
    onChange?: ( args: onChangeArgs ) => void;
  }

export const ProductContext = createContext({} as ProductContextProps);
const { Provider } = ProductContext;

export const ProductCard = 
  ({ children, product, className, style, onChange, value, initialValues }: Props) => {

    const { counter, maxCount, isMaxCountReached, increaseBy, reset } = useProduct({ onChange, product, value, initialValues })

  return (
    <Provider value={{
        counter,
        product,
        maxCount,
        increaseBy,
    }}>
        <div 
            className={ `${styles.productCard} ${className}`}
            style={ style }
            >
            { children({
              count: counter,
              isMaxCountReached,
              maxCount,
              product,
              increaseBy,
              reset
            }) }
        </div>
    </Provider>
  )
}