window.collectionForm = ({
  collectionSelector = '[data-form-type="collection"]',
  maxItems = null,
}) => {
  const deleteItem = (e) => {
    e.preventDefault();

    const deleteBtn = e.target;
    const item = deleteBtn.closest('[data-form-collection="item"]');

    item.parentNode.removeChild(item);
  };

  document.querySelectorAll(collectionSelector).forEach((collection) => {
    const addBtn = collection.querySelector('[data-form-collection="add"]');
    if (!addBtn) {
      return;
    }

    const { prototype } = collection.dataset;
    if (!prototype) {
      throw new Error('No prototype found for collection.');
    }

    const list = collection.querySelector('[data-form-collection="list"]');
    if (!prototype) {
      throw new Error('No list found for collection.');
    }

    list.querySelectorAll('[data-form-collection="delete"]').forEach((deleteBtn) => {
      deleteBtn.addEventListener('click', deleteItem);
    });

    let counter = list.childElementCount;

    addBtn.addEventListener('click', (e) => {
      e.preventDefault();

      if (maxItems && list.childElementCount >= maxItems) {
        return;
      }

      const newItem = prototype.replace(/__name__/g, counter);
      const div = document.createElement('div');
      div.innerHTML = newItem.trim();

      const deleteBtn = div.querySelector('[data-form-collection="delete"]');
      if (deleteBtn) {
        deleteBtn.addEventListener('click', deleteItem);
      }

      const fileInputs = div.querySelector('.custom-file-input');
      if (fileInputs) {
        fileInputs.addEventListener('change', (event) => {
          // eslint-disable-next-line no-param-reassign
          event.target.nextElementSibling.innerText = event.target.files[0].name;
          event.target.nextElementSibling.classList.remove('custom-file-placeholder');
          event.target.parentElement.classList.add('active');
        });
      }

      list.append(div.firstChild);

      counter += 1;
    });
  });
};
