
import React, { CSSProperties, ReactElement } from 'react';
import useProduct from '../hooks/useProduct'
import { Provider } from '../contexts/ProductContext';

import styles from '../styles/styles.module.css'
import { OnChangeArgs, Product } from '../interfaces/Product';

export interface InitialValues  {
  count: number;
  maxCount?: number;
}

export interface ProductCardProps {
  product: Product;
  // children: ReactElement | ReactElement[];
  children: (args: ProductCardHandlers) => ReactElement;
  className?: string;
  style?: CSSProperties;
  onChange?: ({ product, count }: OnChangeArgs) => void;
  value?: number;
  initialValues?: InitialValues;
}

export interface ProductCardHandlers {
  count: number;
  isMaxCountReached: boolean;
  maxCount?: number;
  product: Product;
  
  onIncreaseBy: (value: number) => void;
  onReset: () => void;
}

const ProductCard = ({ children, product, className, style, onChange, value, initialValues } : ProductCardProps) => {
  const {counter, maxCount, isMaxCountReached, handleIncreaseBy, onReset} = useProduct({ product, onChange, value, initialValues })

  return (
    <Provider value={{
      product,
      counter,
      maxCount,
      handleIncreaseBy,
      isMaxCountReached,
    }}>
      <div
        className={`${styles.productCard} ${className ?? ''}`}
        style={style ?? {}}
      >
        {
          children({
            count: counter,
            isMaxCountReached,
            onIncreaseBy: handleIncreaseBy,
            onReset,
            product,
            maxCount,
          })
        }
      </div>
    </Provider>
  )
}

export default ProductCard
