import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { Typography } from "@mui/material";
import { SPACING } from "../../../../data/spacing";
import { killHouseAssignmentInformationAggregateLoadService } from "../../services/killhouse-assignment-information-aggregate-load";
import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { resizeImage } from "../../../../utils/resizeImage";

export const AggregateUploadDoc = ({ isSingular, item, updateTable }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [profileImages, setProfileImages] = useState([]);
  const [profileImg, setProfileImg] = useState();
  const { slaughterGetAggregateLoadInformation } = useSelector(
    (state) => state.slaughterSlice
  );

  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) {
      if (isSingular) {
        dispatch(
          killHouseAssignmentInformationAggregateLoadService({
            image: profileImg,
            bar_key: item.key,
            role: getRoleFromUrl(),
          })
        ).then((r) => {
          setProfileImg(null);
          setProfileImages([]);
          dispatch(CLOSE_MODAL());
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
            if (
              item?.assingmentInformation?.realQuantity &&
              item?.assingmentInformation?.carWeightWithLoadImage
            ) {
              dispatch(
                OPEN_MODAL({
                  title: "بار به تب مدیریت بارها منتقل شد.",
                })
              );
            }
            updateTable(1);
          }
        });
      } else {
        dispatch(
          killHouseAssignmentInformationAggregateLoadService({
            image: profileImg,
            bar_keys: slaughterGetAggregateLoadInformation?.map(
              (item) => item.key
            ),
            role: getRoleFromUrl(),
          })
        ).then((r) => {
          setProfileImg(null);
          setProfileImages([]);
          dispatch(CLOSE_MODAL());
          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);
            if (
              item?.assingmentInformation?.realQuantity &&
              item?.assingmentInformation?.carWeightWithLoadImage
            ) {
              dispatch(
                OPEN_MODAL({
                  title: "بار به تب مدیریت بارها منتقل شد.",
                  // content: "",
                })
              );
            }
          }
        });
      }
    }
  }, [profileImg, profileImages]);

  return (
    <Grid width="100%">
      {!isSingular && (
        <Grid container gap={SPACING.TINY} mb={SPACING.SMALL}>
          <Typography color={"error"}>نکته:</Typography>
          <Typography>
            این سند برای تمامی بارهایی که فاقد سند هستند ثبت خواهد شد.
          </Typography>
        </Grid>
      )}
      <Grid mt={SPACING.SMALL}>
        <ImageUpload
          onChange={factorPaymentHandler}
          images={profileImages}
          maxNumber={1}
          showImages={false}
          title={
            item?.assingmentInformation?.carWeightWithLoadImage
              ? "ویرایش"
              : "ثبت"
          }
        />
      </Grid>
    </Grid>
  );
};
