import React, { useEffect, useState } from "react";
import InputText from "../utils/inputText";
import style from "./productQnty.module.css";
const ProductQnty = (props) => {
  const [qnty, setQnty] = useState(1);
  useEffect(() => {
    if (qnty <= 0) {
      setQnty(1);
      props.onUpdate(1);
    } else if (props.stock === -1 && 999 < qnty) {
      setQnty(999);
      props.onUpdate(999);
    } else if (
      props.stock !== undefined &&
      props.stock !== -1 &&
      props.stock < qnty
    ) {
      setQnty(props.stock);
      props.onUpdate(props.stock);
    } else if (!props.stock && 999 < qnty) {
      setQnty(999);
      props.onUpdate(999);
    } else {
      props.onUpdate(qnty);
    }
  }, [qnty]);
  return (
    <React.Fragment>
      <div className={style.qnty_section}>
        <p onClick={() => setQnty((prev) => Number(prev - 1))}>-</p>
        <InputText
          placeHolder="Enter Qnty"
          value={qnty}
          type="number"
          getValue={(value) => {
            console.log("value: ", value);
            setQnty(Number(value));
            props.onUpdate(Number(value));
          }}
        />
        <p onClick={() => setQnty((prev) => Number(prev + 1))}>+</p>
      </div>
    </React.Fragment>
  );
};

export default ProductQnty;
