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 useUserProfile from "../../../authentication/hooks/useUserProfile";
import { getFileFromApi } from "../../../file/hooks/useRequestFile";
import { provinceEditPoultryRequestService } from "../../services/province-edit-poultry-request-service";
import { provinceGetAllRequests } from "../../services/province-get-all-requests";

export const ProvinceEditPoultryRequestForm = ({
  quantity,
  poultryRequestKey,
}) => {
  const [openNotif] = useContext(AppContext);
  const [roles] = useUserProfile();

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      numberField: quantity,
    },
    onSubmit: (values) => {
      dispatch(
        provinceEditPoultryRequestService({
          quantity: values.numberField,
          key: poultryRequestKey,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          getFileFromApi(roles, poultryRequestKey, dispatch);
          dispatch(provinceGetAllRequests());
          dispatch(CLOSE_MODAL());
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
    validate: (values) => {
      const errors = {};
      if (!values.numberField) {
        errors.numberField = "Field cannot be empty";
      } else if (!/^\d+$/.test(values.numberField)) {
        errors.numberField = "Only numbers are allowed";
      }
      return errors;
    },
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.TINY}>
        <TextField
          fullWidth
          id="numberField"
          label="حداقل تعداد"
          variant="outlined"
          name="numberField"
          value={formik.values.numberField}
          onChange={formik.handleChange}
          error={
            formik.touched.numberField && Boolean(formik.errors.numberField)
          }
          helperText={formik.touched.numberField && formik.errors.numberField}
        />
        <Button type="submit" fullWidth variant="contained">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
