import Repeat from '../classes/Repeat.js';

jQuery(function ($) {

  // Definir o evento para atualização do label do repeat-accordion
  function setHandleChangeLabel(elLabel, elTarget, type) {
    const configHandle = {
      "text": () => elTarget.on('keyup', () => elLabel.text(elTarget.val() || 'Item')).trigger('keyup'),
      "textarea": () => elTarget.on('keyup', () => elLabel.text(elTarget.val() || 'Item')).trigger('keyup'),
      "select": () => elTarget.on('change', () => elLabel.text(elTarget.val() ? elTarget.find('option:selected').text() : 'Item')).trigger('change'),
      "link": () => elTarget.on('change', () => elLabel.text(elTarget.val() || 'Item')).trigger('change'),
      "image": () => elTarget.on('change', () => elLabel.text(elTarget.text() || 'Item')).trigger('change')
    };

    if (configHandle[type])
      configHandle[type]();
  }

  // Configuração do label do label do repeat-accordion
  function configLabel(item) {
    const elLabelConfig = $('.o2-repeat-set-label', item);
    if (elLabelConfig) {
      try {
        const labelConfig = JSON.parse(elLabelConfig.val());
        const elLabel = $('.o2-repeat-item-title', item);
        let elTarget;

        if (labelConfig.type === 'link')
          elTarget = $(`[name="${labelConfig.name}[text]"]`, item);
        else if (labelConfig.type === 'image')
          elTarget = $(`[name="${labelConfig.name}"]`, item).closest('.o2-image-field').find('.o2-image-field-details-title');
        else if (labelConfig.type === 'select')
          elTarget = $(`[name="${labelConfig.name}"]`, item);
        else
          elTarget = $(`[name="${labelConfig.name}"]`, item);

        setHandleChangeLabel(elLabel, elTarget, labelConfig.type);
      } catch (error) {
      }
    }
  }

  function instantiateRepeats(element) {
    $('.o2-repeat', element).each(function () {
      const wrapperRepeat = $(this).children('.o2-repeat-wrapper');
      const repeat = new Repeat(wrapperRepeat.get(0), $(this).parents('.o2-repeat').length);
      $(this).data('repeat', repeat);

      // adicionar o draggable caso tenha a classe
      if ($(this).hasClass('draggable')) {
        $('.o2-repeat-wrapper', this).sortable({
          handle: '.o2-repeat-handle',
          opacity: 0.7,
          update: () => repeat.update()
        });
      }
    });


    $('.o2-repeat-accordion', element).each(function () {
      const wrapper = $(this).children('.o2-repeat-wrapper');
      wrapper.children('.o2-repeat-item').each(function () {
        configLabel(this);
      });
    });
  }

  // Com o carregamento da página
  instantiateRepeats(document);

  // Botão para adicionar
  $(document).on('click', '.o2-repeat-add', function () {
    const repeat = $(this).parent().data('repeat');
    repeat.addItem();
  });

  // Botão para adicionar logo abaixo do item
  $(document).on('click', '.o2-repeat-add-down', function () {
    const repeat = $(this).closest('.o2-repeat').data('repeat');
    let repeatItem = $(this).closest('.o2-repeat-item');
    let index = repeatItem.prevAll().length;
    repeat.addItem(index);
    repeat.update();
  });

  // Botão para remover
  $(document).on('click', '.o2-repeat-remove', function () {
    const repeat = $(this).closest('.o2-repeat').data('repeat');
    if (confirm('Quer remover este item?'))
      repeat.removeItem($(this.parentNode).closest('.o2-repeat-item').get(0));
  });

  // Abrir repeat accordion
  $(document).on('click', '.o2-repeat-item-head', function (event) {
    if ($(event.target).hasClass('material-icons')) return;
    const repeatItem = $(this).closest('.o2-repeat-item');
    repeatItem.children('.o2-repeat-item-body').slideToggle(200).toggleClass('hidden');
    repeatItem.children('.o2-repeat-item-head').find('.o2-repeat-item-indicator span').html(repeatItem.children('.o2-repeat-item-body').hasClass('hidden') ? 'arrow_drop_down' : 'arrow_drop_up');
    // repeatItem.find('.o2-repeat-item-body').slideToggle(200).toggleClass('hidden');
    // repeatItem.find('.o2-repeat-item-indicator span').html(repeatItem.find('.o2-repeat-item-body').hasClass('hidden') ? 'arrow_drop_down' : 'arrow_drop_up');
  });

  // Ações para serem tomadas quando se adicionar um novo item
  $(document).on('RepeatAdd', ({ detail }) => {
    const repeat = detail.repeat;
    const el = detail.el;

    // Incrementando no item index do repeat-item (Removido na V2.4)
    // $(el).find('.o2-repeat-item-index').html($(wrapper).children().length.toString().padStart(2, '0'));

    // Instanciando novos repeat
    instantiateRepeats(el);

    // Configuração do repeat-label
    configLabel(el);

    // Abrir novo item (Caso seja um accordion)
    if ($(repeat).hasClass('o2-repeat-accordion'))
      $(el).children('.o2-repeat-item-head').trigger('click');
  });

  // Ações para serem tomadas quando se exclui um item (Removido na 2.4)
  // $(document).on('RepeatRemove', ({ detail }) => {
  //   const wrapper = $(detail.repeat);
  //   let items = wrapper.children('.o2-repeat-item');
  //   items.each((index, element) => {
  //     $(element).find('.o2-repeat-item-index').html((index + 1).toString().padStart(2, '0'));
  //   });
  // });

});