import React, { useContext, useEffect } from "react";
import { TextField, Button } from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { provinceCheckFreeSaleService } from "../../services/province-check-free-sale";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvinceFreeSalesRejectRequest = ({ item, fetchApiData }) => {
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      textFieldInput: "",
    },
    validationSchema: Yup.object({
      textFieldInput: Yup.string().required("این فیلد اجباری است!"),
    }),
  });

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

  return (
    <Grid xs={12} container justifyContent="center">
      <TextField
        fullWidth
        id="textFieldInput"
        name="textFieldInput"
        label="توضیحات"
        multiline
        rows={4}
        value={formik.values.textFieldInput}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={
          formik.touched.textFieldInput && Boolean(formik.errors.textFieldInput)
        }
        helperText={
          formik.touched.textFieldInput && formik.errors.textFieldInput
        }
        margin="normal"
      />
      <Button
        color="error"
        fullWidth
        variant="contained"
        type="submit"
        disabled={!formik.isValid}
        onClick={() => {
          dispatch(
            provinceCheckFreeSaleService({
              poultry_request_key: item?.key,
              state: "rejected",
              message: formik.values.textFieldInput,
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              dispatch(CLOSE_MODAL());
              fetchApiData(1);
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
