import { Button } from "@mui/material";
import { useFormik } from "formik";
import { useContext, useEffect } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { provinceFinancialGetSlaughterSattlementService } from "../../services/province-financial-get-slaughter-sattlement-service";
import { provinceFinancialSettlmentService } from "../../services/province-financial-settlment";

const validate = (values, maxValue) => {
  const errors = {};
  if (!values.price) {
    errors.price = "این فیلد اجباری است.";
  } else if (!/^[0-9]*$/i.test(values.price)) {
    errors.price = "لطفا عدد وارد کنید.";
  } else if (parseInt(values.price) > parseInt(maxValue)) {
    errors.price = `عدد نمی تواند بزرگتر از ${maxValue} ﷼ باشد.`;
  }
  return errors;
};

export const ProvinceFinancialSettlementSlaughterForm = ({ item }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      price: item.amount,
    },
    validate: (values) => validate(values, item.amount),
    onSubmit: (values) => {
      dispatch(
        provinceFinancialSettlmentService({
          amount: values.price,
          key: item.key,
        })
      ).then((r) => {
        dispatch(provinceFinancialGetSlaughterSattlementService());
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
        dispatch(
          DRAWER({ right: false, bottom: false, content: null, size: null })
        );
      });
    },
  });

  useEffect(() => {
    formik.setFieldValue("price", item.amount);
  }, []);
  return (
    <form onSubmit={formik.handleSubmit} width="100%">
      <Grid>
        <NumberInput
          allowLeadingZeros
          thousandSeparator=","
          fullWidth
          id="price"
          label="مبلغ (﷼)"
          variant="outlined"
          value={formik.values.price}
          error={formik.touched.price ? Boolean(formik.errors.price) : null}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.price && Boolean(formik.errors.price)
              ? formik.errors.price
              : null
          }
        />
      </Grid>
      <Grid mt={SPACING.SMALL}>
        <Button fullWidth color="primary" variant="contained" type="submit">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
