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

export const ProvinceSubSectorCitySharesSharesEdit = ({
  updateTable,
  item,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      percent: item?.percent ? item?.percent : "",
    },
    validationSchema: Yup.object({
      percent: Yup.number()
        .typeError("لطفا فیلد را به درستی وارد کنید!")
        .max(100, "درصد صحیح وارد کنید")
        .required("این فیلد اجباری است!"),
    }),
  });

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

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <TextField
        id="percent"
        label="درصد سهم تعاونی ها (از سهم اتحادیه)"
        variant="outlined"
        sx={{ width: "100%" }}
        value={formik.values.percent}
        error={formik.touched.percent ? Boolean(formik.errors.percent) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.percent && Boolean(formik.errors.percent)
            ? formik.errors.percent
            : null
        }
      />
      <Button
        disabled={!formik.isValid}
        fullWidth
        variant="contained"
        onClick={() => {
          dispatch(
            provinceSubSectorCitySharesSharesService({
              sub_sector_wage_type_key: item?.key,
              percent: formik.values.percent,
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              updateTable();
              dispatch(CLOSE_MODAL());
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        }}
      >
        ویرایش
      </Button>
    </Grid>
  );
};
