import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceKillhousesPaidFeesChangePaymentTypeService } from "../../services/province-killhouses-paid-fee-change-payment-type-service";
import { SPACING } from "../../../../data/spacing";
import { resizeImage } from "../../../../utils/resizeImage";
import { fixBase64 } from "../../../../utils/toBase64";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { Grid } from "../../../../components/grid/Grid";

export const ProvinceWagePaymentTransactionsUploadDoc = ({
  item,
  updateTable,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [profileImages, setProfileImages] = useState([]);
  const [profileImg, setProfileImg] = useState();

  const factorPaymentHandler = (imageList, addUpdateIndex) => {
    if (imageList[0]) {
      const file = imageList[0]?.file;
      resizeImage(file, (resizedDataUrl) => {
        const optimizedBase64 = fixBase64(resizedDataUrl);
        setProfileImg(optimizedBase64);
      });
    }
    setProfileImages(imageList);
  };

  useEffect(() => {
    if (profileImg) {
      dispatch(
        provinceKillhousesPaidFeesChangePaymentTypeService({
          image: profileImg,
          transaction_key: item?.key,
        })
      ).then((r) => {
        setProfileImg(null);
        setProfileImages([]);
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          updateTable(1);
        }
      });
    }
  }, [profileImg, profileImages]);

  return (
    <Grid width="100%">
      <Grid mt={SPACING.SMALL}>
        <ImageUpload
          onChange={factorPaymentHandler}
          images={profileImages}
          maxNumber={1}
          showImages={false}
          title={item?.image ? "ویرایش" : "ثبت"}
        />
      </Grid>
    </Grid>
  );
};
