(function ($) {
  'use strict';

  /**
   * All of the code for your admin-facing JavaScript source
   * should reside in this file.
   *
   * Note: It has been assumed you will write jQuery code here, so the
   * $ function reference has been prepared for usage within the scope
   * of this function.
   *
   * This enables you to define handlers, for when the DOM is ready:
   *
   * $(function() {
   *
   * });
   *
   * When the window is loaded:
   *
   * $( window ).load(function() {
   *
   * });
   *
   * ...and/or other possibilities.
   *
   * Ideally, it is not considered best practise to attach more than a
   * single DOM-ready or window-load handler for a particular page.
   * Although scripts in the WordPress core, Plugins and Themes may be
   * practising this, we should strive to set a better example in our own work.
   */

  jQuery(document).ready(function () {
    let cloned = false;

    jQuery(document).on('focus', '.events-page .datepicker:not(.hasDatepicker)', function () {
      jQuery('.events-page .datepicker').datepicker({
        dateFormat: 'dd.mm.yy',
        firstDay: 1,
      });
    });

    const datepicker = jQuery('.events-page input.timepicker:not(.mtimepicker-clock)');
    if (datepicker.length) {
      datepicker.mTimePicker().mTimePicker('setTime', '00:00');
    }

    jQuery('.events-page').on('click', 'a.bearbeiten', function (e) {
      e.preventDefault();
      jQuery('.events-page #edit-event').hide();
      jQuery.ajax({
        url: events.ajax_url,
        type: 'POST',
        data: {
          id: jQuery(this).attr('id'),
          action: 'get_event_details',
        },
        success: function (data) {
          const parsedData = JSON.parse(data);

          if (parsedData && parsedData.length > 0) {
            const row = parsedData[0];

            const form = jQuery('.events-page #add_event').clone();
            form.find('table').after(`<input type="hidden" name="id" id="id" value="${row['id']}">`);
            form.find('.hasDatepicker').removeAttr('id').removeClass('hasDatepicker');

            const timePickerField =
              '<input type="text" name="event_time" class="timepicker event_time" value="" autocomplete="off">';
            form.find('.mtimepicker-container').replaceWith(timePickerField);

            for (var key of Object.keys(row)) {
              if (key === 'picture_url') {
                const picture_preview = form.find('#picture_preview');
                picture_preview.html(`<img src='${row[key]}'/>`);
                form.find('#picture_remove').show();
              }

              const field = form.find(`[name='${key}']`);
              if (field.attr('type') === 'button' || (key == 'picture' && row[key] == '0')) {
                continue;
              } else if (field.attr('type') === 'checkbox') {
                field.prop('checked', row[key] == '1');

                if (key === 'verlegen' && row[key] == '1') {
                  form.find('.new_date_row').show();
                } else {
                  form.find('.events-page .new_date').val('');
                  form.find('.events-page .new_date_row').hide();
                }
              } else {
                if (key === 'event_date' || key === 'new_date') {
                  if (!isNaN(new Date(row[key]).getTime())) {
                    const formatedDate = $.datepicker.formatDate('dd.mm.yy', new Date(row[key]));
                    field.val(formatedDate);
                  } else {
                    field.val('');
                  }
                } else {
                  field.val(row[key]);
                }
              }
            }

            form.attr('id', 'update_event');
            form.attr('name', 'update_event');
            form.attr('class', 'update_event');
            form.find('.button-submit').val('Update');
            jQuery('.events-page #update_event').replaceWith(form);
            jQuery('.events-page input.timepicker:not(.mtimepicker-clock)')
              .mTimePicker()
              .mTimePicker('setTime', row['event_time'] || '00:00');
          }
          jQuery('.events-page #edit-event, .overlay').show();
        },
        error: function (errorThrown) {
          jQuery('.events-page #edit-event').hide();
          jQuery('.events-page #submit').removeAttr('disabled');
        },
      });
    });

    jQuery('.events-page').on('submit', '#update_event', function (e) {
      e.preventDefault();
      const formData = jQuery('.events-page #update_event').serializeArray();

      formData.map((e) => {
        if (e.name === 'event_date' || e.name === 'new_date') {
          e.value = formatDateGermanToEnglish(e.value);
        }
      });

      if (!formData.some((e) => e.name === 'verlegen')) {
        formData.push({ name: 'verlegen', value: '0' });
      }

      if (!formData.some((e) => e.name === 'status')) {
        formData.push({ name: 'status', value: '0' });
      }

      const id = jQuery('.events-page #update_event input#id').val();

      jQuery.ajax({
        url: events.ajax_url,
        type: 'POST',
        data: {
          id: id,
          data: formData,
          action: 'update_event',
        },
        success: function (data) {
          location.reload();
        },
        error: function (errorThrown) {
          jQuery('.events-page .edit-form').hide();
          jQuery('.events-page #submit').removeAttr('disabled');
        },
      });
    });

    jQuery('.events-page ').on('submit', '#add_event', function (e) {
      e.preventDefault();
      let formData = jQuery('.events-page #add_event').serializeArray();
      formData = formData.filter((e) => e.value != '');

      formData.map((e) => {
        if (e.name === 'event_date' || e.name === 'new_date') {
          e.value = formatDateGermanToEnglish(e.value);
        }
      });

      if (!formData.some((e) => e.name === 'verlegen')) {
        formData.push({ name: 'verlegen', value: '0' });
      }

      if (!formData.some((e) => e.name === 'status')) {
        formData.push({ name: 'status', value: '0' });
      }

      // console.log(formData);

      jQuery.ajax({
        url: events.ajax_url,
        type: 'POST',
        data: {
          data: formData,
          action: 'add_event',
        },
        success: function (data) {
          const parseData = JSON.parse(data);
          if (parseData['status'] == 'false') {
            alert(parseData['error']);
            return false;
          } else {
            location.reload();
          }
        },
        error: function (errorThrown) {
          jQuery('.events-page .edit-form').hide();
          jQuery('.events-page #submit').removeAttr('disabled');
        },
      });
    });

    jQuery('.events-page ').on('click', '#clone_event', function (e) {
      e.preventDefault();

      let formData = jQuery('.events-page #update_event').serializeArray();
      formData = formData.filter((e) => e.name != 'id' && e.value != '');

      if (!formData.some((e) => e.name === 'verlegen')) {
        formData.push({ name: 'verlegen', value: '0' });
      }

      if (!formData.some((e) => e.name === 'status')) {
        formData.push({ name: 'status', value: '0' });
      }

      jQuery.ajax({
        url: events.ajax_url,
        type: 'POST',
        data: {
          data: formData,
          action: 'add_event',
        },
        success: function (data) {
          const parseData = JSON.parse(data);
          if (parseData['status'] == 'false') {
            alert(parseData['error']);
            return false;
          } else {
            cloned = true;
            alert('Event cloned successfully. Please make the necessary changes and update.');
            jQuery('.events-page #clone_event').hide();
            jQuery('.events-page #update_event input#id').val(parseData['id']);
          }
        },
        error: function (errorThrown) {
          jQuery('.events-page .edit-form').hide();
          jQuery('.events-page #submit').removeAttr('disabled');
        },
      });
    });

    jQuery('.events-page ').on('click', '.button-picture', function (e) {
      e.preventDefault();

      var file_frame_trimg;
      var self = jQuery(this);

      if (file_frame_trimg) {
        file_frame_trimg.open();
        return;
      }

      file_frame_trimg = wp.media.frames.file_frame_trimg = wp.media({
        title: jQuery(this).data('uploader_title'),
        button: {
          text: jQuery(this).data('uploader_button_text'),
        },
        multiple: false,
      });

      file_frame_trimg.on('select', function () {
        var attachment = file_frame_trimg.state().get('selection').first().toJSON();

        jQuery(self).siblings('#picture_preview').html(`<img src='${attachment.url}'/>`);
        jQuery(self).siblings('input#picture').val(attachment.id);
        jQuery('.media-modal-close').trigger('click');
        jQuery(self).siblings('#picture_remove').show();
      });

      file_frame_trimg.open();
    });

    jQuery('.events-page').on('change', '#verlegen', function (e) {
      if (this.checked) {
        jQuery('.events-page .new_date_row').show();
      } else {
        jQuery('.events-page .new_date').val('');
        jQuery('.events-page .new_date_row').hide();
      }
    });

    jQuery('.events-page ').on('click', '#picture_remove', function (e) {
      e.preventDefault();

      var self = jQuery(this);

      jQuery(self).siblings('#picture_preview').html('');
      jQuery(self).siblings('input#picture').val('');
      self.hide();

    });

    jQuery('.events-page').on('change', '#verlegen', function (e) {
      if (this.checked) {
        jQuery('.events-page .new_date_row').show();
      } else {
        jQuery('.events-page .new_date').val('');
        jQuery('.events-page .new_date_row').hide();
      }
    });

    jQuery('.events-page').on('click', '.overlay', function (e) {
      if (cloned) {
        location.reload();
      }

      jQuery('.events-page .event_wrapper, .edit-form').hide();
      jQuery('.events-page .overlay').hide();
    });

    jQuery('.events-page').on('click', 'div#Archiv .loschen', function (e) {
      e.preventDefault();
      jQuery.ajax({
        url: events.ajax_url,
        type: 'POST',
        data: {
          id: jQuery(this).attr('id'),
          action: 'delete_event',
        },
        success: function (data) {
          location.reload();
        },
        error: function (errorThrown) {
          alert(errorThrown);
          return false;
        },
      });
    });

    jQuery('.events-page').on('click', 'div#Aktuell .loschen, div#Geplant .loschen', function (e) {
      e.preventDefault();

      let status = '0';

      jQuery.ajax({
        url: events.ajax_url,
        type: 'POST',
        data: {
          id: jQuery(this).attr('id'),
          action: 'update_event_status',
          status: status,
        },
        success: function (data) {
          location.reload();
        },
        error: function (errorThrown) {
          alert(errorThrown);
          return false;
        },
      });
    });

    jQuery('.events-page .overlay').remove();
    jQuery('.events-page .wrap.nosubsub, .events-page .event_wrapper').after(
      "<div class='overlay' style='display:none'></div>"
    );

    jQuery('.events-page').on('click', 'input.button.button-primary.new_event', function () {
      jQuery('.events-page #col-left, .events-page .overlay, .events-page .col-wrap.event_wrapper').show();
    });

    jQuery('.events-page').on('click', 'input#Zuruck', function () {
      if (cloned) {
        location.reload();
      }

      jQuery('.events-page #col-left, .events-page .event_wrapper').hide();
      jQuery('.events-page .edit-form, .events-page .overlay').hide();
    });
  });

  function validateEmail($email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return emailReg.test($email);
  }

  function formatDateGermanToEnglish(dateString) {
    if (!dateString) {
      return '';
    }

    let $date = $.datepicker.parseDate('dd.mm.yy', dateString);
    $date = new Date($date);

    return $.datepicker.formatDate('yy-mm-dd', $date);
  }
})(jQuery);
