import { Button, TextField } from "@mui/material";
import { useFormik } from "formik";
import { useContext } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getSlaughterHousesRequest } from "../../../file/services/getSlaughterHousesRequest";
import { provinceEditKillCapacityService } from "../../services/province-edit-kill-capacity";

export const ProvinceEditKillCapacityForm = ({
  killRequestKey,
  poultryRequestKey,
  killCapacity,
  updateTable,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      number: killCapacity,
    },
    onSubmit: (values) => {
      dispatch(
        provinceEditKillCapacityService({
          kill_request_key: killRequestKey,
          quantity: values.number,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          dispatch(getSlaughterHousesRequest(poultryRequestKey));
          dispatch(CLOSE_MODAL());
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          updateTable();
        }
      });
    },
    validate: (values) => {
      const errors = {};
      if (!values.number) {
        errors.number = "این فیلد اجباری است";
      } else if (isNaN(parseInt(values.number))) {
        errors.number = "باید عدد وارد شود.";
      }
      return errors;
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.SMALL}>
        <TextField
          fullWidth
          variant="outlined"
          label="ظرفیت کل"
          name="number"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.number}
          error={formik.touched.number && Boolean(formik.errors.number)}
          helperText={formik.touched.number && formik.errors.number}
        />
        <Button fullWidth variant="contained" type="submit">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
