import React, { useContext } from "react";
import { TextField, Button, Grid } from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import {
  provinceGetAllocatedRequestsService,
  provinceUpdateAllocatedRequestService,
} from "../../services/province-get-allocated-requests";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const ProvinceAllocatedRequestsEditAllocation = ({
  selectedDate1,
  selectedDate2,
  item,
  fetchDashboard,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      amount: item.allocatedQuantity ? item.allocatedQuantity : "",
    },
    validationSchema: Yup.object({
      amount: Yup.number()
        .required("وارد کردن حجم الزامی است")
        .min(1, "حجم باید بزرگتر از صفر باشد"),
    }),
    onSubmit: (values) => {
      dispatch(
        provinceUpdateAllocatedRequestService({
          edit_allocation_quantity: true,
          province_kill_request_key: item?.provinceKillRequestKey,
          quantity: parseInt(values?.amount),
          role: getRoleFromUrl(),
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          dispatch(
            provinceGetAllocatedRequestsService({
              selectedDate1,
              selectedDate2,
            })
          );
          fetchDashboard();
          dispatch(CLOSE_MODAL());
        }
      });
    },
  });

  return (
    <Grid
      container
      spacing={2}
      direction="column"
      alignItems="center"
      justifyContent="center"
    >
      <Grid item xs={12}>
        <form onSubmit={formik.handleSubmit}>
          <TextField
            fullWidth
            id="amount"
            name="amount"
            label="حجم"
            value={formik.values.amount}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.amount && Boolean(formik.errors.amount)}
            helperText={formik.touched.amount && formik.errors.amount}
            variant="outlined"
          />
          <Button
            fullWidth
            type="submit"
            variant="contained"
            color="primary"
            style={{ marginTop: "16px" }}
          >
            ارسال
          </Button>
        </form>
      </Grid>
    </Grid>
  );
};
