import { Button } from "@mui/material";
import { useFormik } from "formik";
import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { SPACING } from "../../../../data/spacing";
import { Yup } from "../../../../lib/yup/yup";
import { fixBase64 } from "../../../../utils/toBase64";
import { PropTypes } from "prop-types";
import { useDispatch } from "react-redux";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { depositeAllocation } from "../../services/deposite-allocation";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceFinancialGetFinalFactorsService } from "../../../province-finacial/services/province-financial-get-final-factors-service";

export const FactorPaymentShareDrawer = ({
  share,
  allocationKey,
  paymentPrice,
  fileId,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      factorImg: "",
      payment: paymentPrice,
    },
    validationSchema: Yup.object({
      factorImg: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      payment: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
    }),
  });

  const [factorImgs, setFactorImgs] = useState([]);

  const factorImgHandler = (imageList, addUpdateIndex) => {
    if (imageList[0]) {
      formik.setFieldValue("factorImg", fixBase64(imageList[0]?.data_url));
    } else {
      formik.setFieldValue("factorImg", "");
    }
    setFactorImgs(imageList);
  };

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

  return (
    <Grid container gap={SPACING.SMALL} justifyContent="center">
      <NumberInput
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        label="مبلغ پرداختی"
        name="payment"
        id="payment"
        variant="outlined"
        InputProps={{
          readOnly: true,
        }}
        value={formik.values.payment}
        error={formik.touched.payment ? Boolean(formik.errors.payment) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.payment && Boolean(formik.errors.payment)
            ? formik.errors.payment
            : null
        }
      />
      <Grid>
        <ImageUpload
          onChange={factorImgHandler}
          images={factorImgs}
          maxNumber={1}
          title={"بارگذاری سند"}
        />
      </Grid>
      <Button
        fullWidth
        variant="contained"
        disabled={!formik.isValid}
        onClick={() => {
          dispatch(LOADING_START());
          dispatch(
            depositeAllocation({
              key: allocationKey,
              type: share,
              image: formik.values.factorImg,
              payment: formik.values.payment,
            })
          ).then((r) => {
            if (r.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "مشکلی پیش آمده است!",
                severity: "error",
              });
            } else {
              dispatch(provinceFinancialGetFinalFactorsService());
              dispatch(CLOSE_MODAL());
              dispatch(LOADING_END());
              // getFileFromApi(roles, fileId, dispatch);
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};

FactorPaymentShareDrawer.propTypes = {
  share: PropTypes.string,
  allocationKey: PropTypes.string,
  paymentPrice: PropTypes.any,
  fileId: PropTypes.any,
};
