import React, { useContext } from "react";
import { TextField, Button, Typography } from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceJahadEditRancher } from "../../services/province-jahad-rancher-activation";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

const validationSchema = Yup.object({
  amount: Yup.number()
    .required("تعداد الزامی است")
    .integer("تعداد باید یک عدد صحیح باشد"),
});

export const ProvinceJahadSubmitDhi = ({
  updateTable,
  item,
  getDashboardData,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const formik = useFormik({
    initialValues: {
      amount: item?.dhiAmount || "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(
        provinceJahadEditRancher({
          key: item?.key,
          dhi_amount: values.amount,
        })
      ).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(CLOSE_MODAL());
          getDashboardData();
          updateTable();
        }
      });
    },
  });

  return (
    <Grid container xs={12} justifyContent="center">
      <Typography variant="body2" color="error">
        در صورت وارد کردن مقدار 0 دامدار از پروژه DHI خارج میشود.
      </Typography>
      <TextField
        fullWidth
        id="amount"
        name="amount"
        label="تعداد دام DHI"
        variant="outlined"
        margin="normal"
        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}
      />
      <Button
        type="submit"
        variant="contained"
        color="primary"
        fullWidth
        onClick={formik.handleSubmit}
      >
        ثبت
      </Button>
    </Grid>
  );
};
