let _sortType = "";

jQuery(($) => {
  const appendFirstBlock = () => {
    const countElements = $("#flothemes_gallery_metabox-list .fgt-gallery-item")
      .length;
    if (countElements > 0) {
      if (
        $("#flothemes_gallery_metabox-list .fgt-gal-first-child").length > 0
      ) {
        return;
      } else {
        $("#flothemes_gallery_metabox-list").prepend(
          '<li class="fgt-gal-first-child"><i class="fgt-icon-image-add"></i></li>'
        );
        $(".gallery-add.button").addClass("hidden");
      }
    } else {
      $("#flothemes_gallery_metabox-list .fgt-gal-first-child").remove();
      $(".gallery-add.button").removeClass("hidden");
    }
  };
  if ($("#flothemes_gallery_metabox-list .fgt-gal-first-child").length > 0) {
    $(".gallery-add.button").addClass("hidden");
  }
  let file_frame;

  $(document).on(
    "click",
    "#flothemes_gallery_metabox a.gallery-add, .fgt-gal-first-child",
    (e) => {
      e.preventDefault();

      if (file_frame) file_frame.close();

      file_frame = wp.media.frames.file_frame = wp.media({
        library: {type: "image"},
        title: $(this).data("uploader-title"),
        button: {
          text: $(this).data("uploader-button-text"),
        },
        multiple: "add",
      });

      file_frame.on("select", () => {
        const listIndex = $("#flothemes_gallery_metabox-list li").index(
            $("#flothemes_gallery_metabox-list li:last")
          ),
          selection = file_frame.state().get("selection");
        let selectedIds = [];
        $("#flothemes_gallery_metabox-list").html("");
        selection.map((attachment, i) => {
          const image = attachment.toJSON();
          const index = listIndex + (i + 1);
          selectedIds.push(image.id);
          const imageSrc = image?.sizes?.thumbnail?.url || image.url;
          const imageFilePath = image.url.split("uploads/").pop();

          return $("#flothemes_gallery_metabox-list").append(
            `<li class="fgt-gallery-item" data-file="${imageFilePath}">
              <input type="hidden" name="_post_image_gallery[${index}]" value="${image.id}">
              <img class="image-preview" src="${imageSrc}">
              <a class="change-image button button-small" href="#" data-uploader-title="Change image" data-uploader-button-text="Change image">
                <i class="fgt-icon-reload"></i>
              </a>
              <a class="remove-image" href="#">
                <i class="fgt-icon-trash"></i>
              </a>
            </li>`
          );
        });

        doSortGalleryImages(_sortType);
        $("#gallery_ids").val(JSON.stringify(selectedIds));

        setTimeout(() => {
          appendFirstBlock();
        }, 250);
      });

      file_frame.on("open", () => {
        const allImages = $(".fgt-gallery-item > input[type=hidden]");

        let imagesArray = [];
        if (typeof allImages !== "undefined") {
          allImages.map((index, item) => {
            imagesArray.push(item.value);
          });
        }
        const selectionAPI = file_frame.state().get("selection");

        if (allImages.length > 0) {
          let imagesQuery = wp.media.model.Query.get({
            include: imagesArray.map((id) => parseInt(id)),
            posts_per_page: 1000,
            orderby: "post__in",
          });
          imagesQuery.fetch().then((imagesResult) => {
            imagesResult.forEach((image) => {
              const attachment = wp.media.attachment(image.id);
              selectionAPI.add(attachment ? [attachment] : []);
            });
          });
        }
      });

      makeSortable();
      file_frame.open();
    }
  );

  $(document).on(
    "click",
    "#flothemes_gallery_metabox a.change-image",
    function (e) {
      e.preventDefault();

      var that = $(this);

      if (file_frame) file_frame.close();

      file_frame = wp.media.frames.file_frame = wp.media({
        title: $(this).data("uploader-title"),
        button: {
          text: $(this).data("uploader-button-text"),
        },
        multiple: false,
      });

      file_frame.on("select", function () {
        const attachment = file_frame.state().get("selection").first().toJSON();

        that.parent().find("input:hidden").attr("value", attachment.id);

        console.log(that.parent().find("input:hidden"));
        that
          .parent()
          .find("img.image-preview")
          .attr("src", attachment.sizes.thumbnail.url);
      });

      file_frame.open();
    }
  );

  function resetIndex() {
    $("#flothemes_gallery_metabox-list li").each(function (i) {
      $(this)
        .find("input:hidden")
        .attr("name", "_post_image_gallery[" + i + "]");
    });
  }

  function makeSortable() {
    $("#flothemes_gallery_metabox-list").sortable({
      items: ".fgt-gallery-item",
      opacity: 0.6,
      stop: function () {
        _sortType = "none";
        doSelectOption(_sortType);
        resetIndex();
      },
    });
  }

  $(document).on(
    "click",
    "#flothemes_gallery_metabox a.remove-image",
    function (e) {
      e.preventDefault();

      $(this)
        .parents("li")
        .animate({opacity: 0}, 200, function () {
          $(this).remove();
          resetIndex();
        });
      setTimeout(() => {
        appendFirstBlock();
      }, 250);
    }
  );

  makeSortable();

  /**
   * Sorts gallery images by sorting type
   * @param {String} type
   */
  function doSortGalleryImages(type) {
    if (type === "none" || type.length === 0) return;
    const imagesContainerSelector = "#flothemes_gallery_metabox-list";
    const imagesContainer = document.querySelector(imagesContainerSelector);

    const images = document.getElementsByClassName("fgt-gallery-item");
    let imagesArray = Array.from(images);

    imagesArray.forEach((image) => {
      imagesContainer.removeChild(image);
    });

    imagesArray = imagesArray.sort((a, b) => {
      const aFilePath = a.dataset.file.split("/");
      const bFilePath = b.dataset.file.split("/");

      const aFileName = aFilePath.pop().toLowerCase();
      const bFileName = bFilePath.pop().toLowerCase();

      const aUploadDate = aFilePath.join("/");
      const bUploadDate = bFilePath.join("/");

      if (type === "ascending") return aFileName > bFileName ? 1 : -1;
      if (type === "descending") return aFileName < bFileName ? 1 : -1;
      return aUploadDate < bUploadDate ? 1 : -1;
    });

    imagesArray.forEach((image) => {
      imagesContainer.appendChild(image);
    });
  }

  const sortingContainerSelector = ".flothemes_gallery_sorting_select";
  const sortingContainer = $(sortingContainerSelector);

  const selectElement = $(sortingContainer).find(".select");
  const selectElementOptions = selectElement.find(".select-option");
  const selectElementTrigger = $(sortingContainer).find(".select-trigger");

  function doSelectOption(optionValue) {
    const selectedOption = selectElement.find(".select-option.selected");
    if (selectedOption.data("value") === optionValue) return;
    $(selectedOption).removeClass("selected");

    const optionSelector = `.select-option[data-value="${optionValue}"]`;
    const option = selectElement.find(optionSelector);
    option.addClass("selected");

    selectElementTrigger.find("span").text(option.text());
  }

  sortingContainer.on("click", () => {
    selectElement.toggleClass("open");
  });

  selectElementOptions.each((_, option) => {
    $(option).on("click", function () {
      const optionValue = option.dataset.value;
      doSelectOption(optionValue);
      doSortGalleryImages(optionValue);
      _sortType = optionValue;
    });
  });

  $(window).on("click", (e) => {
    if (selectElement.get(0).contains(e.target)) return;
    selectElement.removeClass("open");
  });
});
