import { useFormik } from "formik";
import { Grid } from "../../../components/grid/Grid";
import { Button, InputAdornment, TextField } from "@mui/material";
import { Yup } from "../../../lib/yup/yup";
import { useContext, useEffect } from "react";
import { SPACING } from "../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";
import { guildUpdateAllocatedStockService } from "../services/guild-update-allocated-stock";
import { AppContext } from "../../../contexts/AppContext";
import { guildGetInventoryStockService } from "../services/guild-get-inventory-stock";
import { guildGetInventoryAllocatedService } from "../services/guild-get-inventory-allocated";
import { CLOSE_MODAL } from "../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../utils/getRoleFromUrl";
import { senfGetInventoryStockService } from "../services/senf-get-inventory-stock";
import { senfGetInventoryAllocatedService } from "../services/senf-get-inventory-allocated";
import { checkPathStartsWith } from "../../../utils/checkPathStartsWith";

const schema = Yup.object().shape({
  quantity: Yup.number().required("وارد کردن تعداد اجباری است"),
  weight: Yup.number().required("وارد کردن وزن اجباری است"),
});

export const RegisterEditDeliveryNumberAndWeight = ({ item }) => {
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1] = useContext(AppContext);
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const formik = useFormik({
    initialValues: {
      quantity: item?.receiverRealNumberOfCarcasses,
      weight: item?.receiverRealWeightOfCarcasses,
    },
    validationSchema: schema,
    onSubmit: (values) => {
      dispatch(
        guildUpdateAllocatedStockService({
          steward: true,
          allocation_key: item.key,
          receiver_real_number_of_carcasses: Number(values.quantity),
          receiver_real_weight_of_carcasses: Number(values.weight),
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          if (getRoleFromUrl() === "senf") {
            dispatch(
              senfGetInventoryStockService({
                date: selectedDate1,
              })
            );
            dispatch(
              senfGetInventoryAllocatedService({
                date: selectedDate1,
              })
            );
          } else {
            dispatch(
              guildGetInventoryStockService({
                date: selectedDate1,
                role_key: checkPathStartsWith("senf")
                  ? selectedSubUser?.key
                  : "",
              })
            );
            dispatch(
              guildGetInventoryAllocatedService({
                date: selectedDate1,
                role_key: checkPathStartsWith("senf")
                  ? selectedSubUser?.key
                  : "",
              })
            );
          }
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          dispatch(CLOSE_MODAL());
        }
      });
    },
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  useEffect(() => {
    const quantity = formik.values.weight / item.indexWeight;
    formik.setFieldValue("quantity", quantity.toFixed(0));
  }, [formik.values.weight]);

  return (
    <Grid container direction="column" width="100%">
      <form onSubmit={formik.handleSubmit}>
        <Grid container gap={SPACING.SMALL}>
          <TextField
            id="weight"
            name="weight"
            label="وزن واقعی تحویلی"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">کیلوگرم</InputAdornment>
              ),
            }}
            value={formik.values.weight}
            onChange={formik.handleChange}
            error={formik.touched.weight && formik.errors.weight}
            helperText={formik.touched.weight && formik.errors.weight}
          />
          <TextField
            id="quantity"
            name="quantity"
            label="تعداد واقعی تحویلی"
            disabled={true}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">قطعه</InputAdornment>
              ),
            }}
            value={formik.values.quantity}
            onChange={formik.handleChange}
            error={formik.touched.quantity && formik.errors.quantity}
            helperText={formik.touched.quantity && formik.errors.quantity}
          />
          <Button type="submit" fullWidth variant="contained">
            ثبت
          </Button>
        </Grid>
      </form>
    </Grid>
  );
};
