import { Button, Grid } from "@mui/material";
import { useFormik } from "formik";
import { useContext, useEffect } from "react";
import { useDispatch } from "react-redux";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { avicultureHatchingRequestsService } from "../../../aviculture/services/aviculture-hatching-requests";
import { avicultureGetRequests } from "../../../aviculture/services/aviculture-requests";
import { updateKillPoultryRequest } from "../../../province/services/update-kill-poultry-request";
import { cityGetHatchings } from "../../services/city-get-hatchings";
import { getSlaughtersKillRequestService } from "../../services/get-slaughters-kill-request";

export const CityUpdateKillRequest = ({ item, updateTable }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      quantity: "",
    },
    validate: (values) => {
      const errors = {};

      if (!values.quantity) {
        errors.quantity = "Required";
      } else if (isNaN(values.quantity)) {
        errors.quantity = "Must be a number";
      }
      // else if (
      //   values.quantity > item.process?.poultry?.poultryPreviousQuantity
      // ) {
      //   errors.quantity =
      //     "Quantity cannot be greater than poultryPreviousQuantity";
      // } else if (0 >= item.process?.poultry?.poultryRemainQuantity) {
      //   errors.quantity =
      //     "Quantity cannot be greater than poultryPreviousQuantity";
      // }

      return errors;
    },
    onSubmit: (values) => {
      // console.log(values);
    },
  });

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

  useEffect(() => {
    formik.setFieldValue("quantity", item.quantity);
  }, [item.quantity]);

  return (
    <Grid direction="row" display="flex" key="ooo">
      <NumberInput
        allowLeadingZeros
        thousandSeparator=","
        id="quantity"
        onChange={formik.handleChange}
        value={formik.values.quantity}
        style={{ width: 80, textAlign: "center" }}
      />
      <Button
        disabled={!formik.isValid}
        onClick={() => {
          dispatch(
            updateKillPoultryRequest({
              key: item.key,
              quantity: Number(formik.values.quantity),
              state: "accepted_quantity",
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              dispatch(CLOSE_MODAL());
              updateTable();
              dispatch(
                avicultureHatchingRequestsService({
                  selectedDate1,
                  selectedDate2,
                })
              );
              dispatch(getSlaughtersKillRequestService());
              dispatch(avicultureGetRequests());
              dispatch(cityGetHatchings(getRoleFromUrl()));
              dispatch(avicultureGetRequests());
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
