import React, { useContext } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { TextField, Button } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { liveStockChangeFreezingState } from "../../services/live-stock-change-freezing-state";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const LiveStockEnterQuantityWeight = ({ item, fetchApi }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const validationSchema = yup.object({
    quantity: yup
      .number()
      .required("مقدار اجباری است")
      .positive("عدد مثبت وارد کنید"),
    weight: yup
      .number()
      .required("وزن اجباری است")
      .positive("عدد مثبت وارد کنید"),
  });
  const formik = useFormik({
    initialValues: {
      quantity: item.quantity ? item?.quantity : "",
      weight: item.weight ? item?.weight : "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(
        liveStockChangeFreezingState({
          allocation_key: item?.key,
          role: getRoleFromUrl(),
          state: "accepted",
          accepted_quantity: parseInt(formik.values.quantity),
          accepted_weight: parseInt(formik.values.weight),
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          fetchApi();
          dispatch(CLOSE_MODAL());
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={2}>
        <TextField
          fullWidth
          id="quantity"
          name="quantity"
          label="مقدار"
          value={formik.values.quantity}
          onChange={formik.handleChange}
          error={formik.touched.quantity && Boolean(formik.errors.quantity)}
          helperText={formik.touched.quantity && formik.errors.quantity}
        />
        <TextField
          fullWidth
          id="weight"
          name="weight"
          label="وزن"
          value={formik.values.weight}
          onChange={formik.handleChange}
          error={formik.touched.weight && Boolean(formik.errors.weight)}
          helperText={formik.touched.weight && formik.errors.weight}
        />
        <Button type="submit" variant="contained" color="primary" fullWidth>
          ارسال
        </Button>
      </Grid>
    </form>
  );
};
