import { Button, TextField } from "@mui/material";
import { useFormik } from "formik";
import { useContext, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { Yup } from "../../../../lib/yup/yup";
import { slaughterGetInventoryStock } from "../../services/salughter-get-inventory-stock";
import { slaughterEditStockService } from "../../services/slaughter-edit-stock";

const NumberValidationSchema = Yup.object().shape({
  firstNumber: Yup.number()
    .required("حجم لاشه ها الزامی می باشد")
    .min(0, "Number must be greater than or equal to 0"),
  secondNumber: Yup.number()
    .required("موجودی وزن لاشه ها الزامی می باشد")
    .min(0, "Number must be greater than or equal to 0"),
});

export const SlaughterEditStock = ({ inventoryKey, aveWeightOfCarcasses }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1] = useContext(AppContext);

  const { inventorySelectedKillHouse } = useSelector(
    (state) => state.slaughterSlice
  );

  const formik = useFormik({
    initialValues: {
      firstNumber: "",
      secondNumber: "",
    },
    validationSchema: NumberValidationSchema,
    onSubmit: (values) => {
      dispatch(
        slaughterEditStockService({
          key: inventoryKey,
          updated_number_of_carcasses: Number(values.firstNumber),
          updated_weight_of_carcasses: Number(values.secondNumber),
        })
      ).then((r) => {
        dispatch(
          slaughterGetInventoryStock({
            date: selectedDate1,
            kill_house_key: inventorySelectedKillHouse,
          })
        );
        if (r.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.error,
            severity: "error",
          });
        } else {
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

  useEffect(() => {
    let quantity;
    if (aveWeightOfCarcasses) {
      quantity = formik.values.secondNumber / aveWeightOfCarcasses;
    } else {
      quantity = formik.values.secondNumber / 2;
    }
    formik.setFieldValue("firstNumber", Number(quantity).toFixed());
  }, [formik.values.secondNumber]);

  return (
    <Grid container direction="column">
      <form
        onSubmit={formik.handleSubmit}
        style={{
          display: "flex",
          flexDirection: "column",
          gap: SPACING.LARGE,
        }}
      >
        <Grid container direction="column" gap={SPACING.SMALL}>
          <TextField
            id="secondNumber"
            name="secondNumber"
            label="موجودی وزن لاشه ها (افت 25٪)"
            type="number"
            value={formik.values.secondNumber}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.secondNumber && Boolean(formik.errors.secondNumber)
            }
            helperText={
              formik.touched.secondNumber && formik.errors.secondNumber
            }
          />

          <TextField
            id="firstNumber"
            name="firstNumber"
            label="حجم لاشه ها"
            type="number"
            value={formik.values.firstNumber}
            disabled={true}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.firstNumber && Boolean(formik.errors.firstNumber)
            }
            helperText={formik.touched.firstNumber && formik.errors.firstNumber}
          />

          <Button type="submit" fullWidth variant="contained" color="primary">
            ثبت
          </Button>
        </Grid>
      </form>
    </Grid>
  );
};
