import { useEffect } from "react";
import { Gallery } from "react-grid-gallery";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { getJobMedia } from "../../redux/media/media.actions";
import { selectAllMedia } from "../../redux/media/media.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  allMedia: selectAllMedia
});

const mapDispatchToProps = (dispatch) => ({
  getJobMedia: (id) => dispatch(getJobMedia(id))
});

export default connect(mapStateToProps, mapDispatchToProps)(JobDocumentsLocalGalleryExternal);

function JobDocumentsLocalGalleryExternal({ jobId, externalMediaState, getJobMedia, allMedia }) {
  const [galleryImages, setgalleryImages] = externalMediaState;
  const { t } = useTranslation();

  useEffect(() => {
    if (jobId) {
      getJobMedia(jobId);
    }
  }, [jobId, getJobMedia]);

  useEffect(() => {
    let documents = allMedia?.[jobId]
      ? allMedia[jobId].reduce((acc, val) => {
          if (val.type?.mime && val.type.mime.startsWith("image")) {
            acc.push({ ...val, src: val.thumbnail, fullsize: val.src });
          }
          return acc;
        }, [])
      : [];
    console.log(
      "🚀 ~ file: jobs-documents-local-gallery.external.component.jsx:48 ~ useEffect ~ documents:",
      documents
    );

    setgalleryImages(documents);
  }, [allMedia, jobId, setgalleryImages, t]);

  return (
    <div className="clearfix">
      <Gallery
        images={galleryImages}
        onSelect={(index) => {
          setgalleryImages(galleryImages.map((g, idx) => (index === idx ? { ...g, isSelected: !g.isSelected } : g)));
        }}
      />
    </div>
  );
}
