import {showValidationErrors, clearValidationErrors} from "./utils/validation";
import {callAction} from './utils/http-action';
import {ROUTES} from './utils/routes';
import {appendLoader, showLoader, hideLoader} from "./utils/loader";

var Wick = window.Wick || {};

Wick.ProjectListNote = {
  DEFAULT_MAX_LENGTH: 250,
  PRINTABLE_CHARACTERS_REGEX: /^[\x20-\x7E\xA1-\xFF\n\r]+$/,
  ERROR_MESSAGE_INVALID: 'Please enter a valid project note',
  HIDDEN_CLASS_NAME: 'd-none',
  INPUT_Y_AXEL_PADDINGS: 14,
  NEW_LINE_HEIGHT: 22,
  previousValue: '',
  el: {
    noteForm: '#note-form',
    noteArea: '#project-list-note',
    noteCount: '.note-count',
    btnAddNote: '.btn-add-note',
    btnSaveNote: '.btn-save-note',
    btnCloseNote: '.btn-close-note',
    btnEditNote: '.btn-edit-note',
    btnRemoveNote: '.btn-remove-note',
    noteField: '.note__field',
    note: '.note',
    noteAdd: 'note-add',
    noteEdit: 'note-edit',
    noteSaved: 'note-saved',
    loader: '.loader-wrapper',
  },
  loaderPayload: {
    wrapper: '.note',
    hidden: true,
  },
  getTextareaValueRaw() {
    return $(Wick.ProjectListNote.el.noteArea).val();
  },
  getTextareaValue() {
    return Wick.ProjectListNote.getTextareaValueRaw().trim();
  },
  isNoteValueValid() {
    const noteValue = Wick.ProjectListNote.getTextareaValue();
    return noteValue.length > 0 && Wick.ProjectListNote.PRINTABLE_CHARACTERS_REGEX.test(noteValue);
  },
  setHeightForTextarea() {
    const noteTextArea = $(Wick.ProjectListNote.el.noteArea)[0];
    if(!noteTextArea) {
      return;
    }
    const minHeight = getComputedStyle(noteTextArea).minHeight;
    noteTextArea.style.height = minHeight;
    noteTextArea.style.height = `${noteTextArea.scrollHeight}px`;
  },
  updateCounterForRemainingCharacters() {
    const currentValue = Wick.ProjectListNote.getTextareaValueRaw();
    const currentLength = currentValue.length;
    const maxLength = $(Wick.ProjectListNote.el.noteArea).attr('maxlength');
    const availableNumber = maxLength - currentLength;

    $(Wick.ProjectListNote.el.noteCount).text(availableNumber);
  },
  showEditState(e) {
    e.preventDefault();

    Wick.ProjectListNote.resetStates();
    Wick.ProjectListNote.updateCounterForRemainingCharacters();
    Wick.ProjectListNote.setPreviousValue();
    $(Wick.ProjectListNote.el.note).addClass(Wick.ProjectListNote.el.noteEdit);
  },
  removeNote(e) {
    e.preventDefault();

    showLoader('.project-list__loader');

    if (!Wick.checkLocalEnv) {
      const payload = {
        url: ROUTES.PL_REMOVE_REFERENCE,
        type: 'POST',
        data: {
          shoppingListGuid: window.shoppingListGuid,
        },
        error: function() {
          Wick.ProjectListNote.showError(window.notesRemoveError);
        },
      }

      callAction(payload, Wick.ProjectListNote.showAddState);
    } else {
      setTimeout(() => {
        Wick.ProjectListNote.showAddState();
      }, 3000);
    }
  },
  showAddState() {
    Wick.ProjectListNote.resetStates();
    $(Wick.ProjectListNote.el.note).addClass(Wick.ProjectListNote.el.noteAdd);
    Wick.ProjectListNote.resetField();
    hideLoader();
  },
  closeNote(e) {
    e.preventDefault();

    if (Wick.ProjectListNote.previousValue) {
      Wick.ProjectListNote.showSavedState();
      Wick.ProjectListNote.setNoteValueFromPreviousValue();
      Wick.ProjectListNote.setHeightForTextarea();
    } else {
      Wick.ProjectListNote.showAddState();
    }
  },
  saveNote(e) {
    e.preventDefault();

    const text = Wick.ProjectListNote.getTextareaValue();
    const trimmedText = text.replace(/^\n+|\n+$/g,'');
    $(Wick.ProjectListNote.el.noteArea).val(trimmedText);
    Wick.ProjectListNote.setHeightForTextarea();

    if (Wick.ProjectListNote.isNoteValueValid()) {
      showLoader('.project-list__loader');
      if (!Wick.checkLocalEnv) {
        const payload = {
          url: ROUTES.PL_UPDATE_REFERENCE,
          type: 'POST',
          data: {
            notes: Wick.ProjectListNote.getTextareaValue(),
            shoppingListGuid: window.shoppingListGuid,
          },
          error: function() {
            Wick.ProjectListNote.showError(window.notesUpdateError);
          },
        }

        callAction(payload, Wick.ProjectListNote.showSavedState);
      } else {
        setTimeout(() => {
          Wick.ProjectListNote.showSavedState();
        }, 3000);
      }
    } else {
      Wick.ProjectListNote.showError(Wick.ProjectListNote.ERROR_MESSAGE_INVALID);
    }
  },
  showSavedState() {
    Wick.ProjectListNote.updateNoteValue()
    Wick.ProjectListNote.resetStates();
    Wick.ProjectListNote.disableField();
    $(Wick.ProjectListNote.el.note).addClass(Wick.ProjectListNote.el.noteSaved);
    hideLoader();
  },
  showError(errorMessage) {
    showValidationErrors(Wick.ProjectListNote.el.noteForm, errorMessage);
  },
  resetStates() {
    $(Wick.ProjectListNote.el.note).removeClass(Wick.ProjectListNote.el.noteAdd);
    $(Wick.ProjectListNote.el.note).removeClass(Wick.ProjectListNote.el.noteEdit);
    $(Wick.ProjectListNote.el.note).removeClass(Wick.ProjectListNote.el.noteSaved);
    Wick.ProjectListNote.enableField();
    clearValidationErrors(Wick.ProjectListNote.el.noteForm);
  },
  resetField() {
    $(Wick.ProjectListNote.el.noteArea).val('');
    $(Wick.ProjectListNote.el.noteArea).removeAttr('style');
    Wick.ProjectListNote.resetNoteValue();
  },
  disableField() {
    $(Wick.ProjectListNote.el.noteArea).attr('readonly', 'true');
  },
  enableField() {
    $(Wick.ProjectListNote.el.noteArea).removeAttr('readonly');
  },
  definedNoteLimit() {
    const $noteTextArea = $(Wick.ProjectListNote.el.noteArea);
    const defaultMaxLength = Wick.ProjectListNote.DEFAULT_MAX_LENGTH;
    const noteMaxLengthAttributeValue = $noteTextArea.attr('maxlength');
    const newMaxLength = noteMaxLengthAttributeValue || defaultMaxLength;

    if (newMaxLength !== noteMaxLengthAttributeValue) {
      $noteTextArea.attr('maxlength', newMaxLength);
    }
  },
  checkInitialValue() {
    const isValueExist = !!$(Wick.ProjectListNote.el.noteArea).attr('value');

    if (isValueExist) {
      Wick.ProjectListNote.setNoteValueFromValueAttribute();
      Wick.ProjectListNote.showSavedState();
    }
  },
  setNoteValueFromValueAttribute() {
    const value = $(Wick.ProjectListNote.el.noteArea).attr('value') || '';
    $(Wick.ProjectListNote.el.noteArea).val(value);
  },
  setPreviousValue() {
    Wick.ProjectListNote.previousValue = $(Wick.ProjectListNote.el.noteArea).val();
  },
  setNoteValueFromPreviousValue() {
    const noteValue = $(Wick.ProjectListNote.el.noteArea).val();

    if (noteValue !== Wick.ProjectListNote.previousValue) {
      $(Wick.ProjectListNote.el.noteArea).val(Wick.ProjectListNote.previousValue);
    }
  },
  updateNoteValue() {
    const currentValue = $(Wick.ProjectListNote.el.noteArea).val();
    $(Wick.ProjectListNote.el.noteArea).attr('value', currentValue);
  },
  resetNoteValue() {
    $(Wick.ProjectListNote.el.noteArea).attr('value', '');
  },
  handleNoteInput(event) {
    Wick.ProjectListNote.updateCounterForRemainingCharacters();
    Wick.ProjectListNote.setHeightForTextarea(event);
    clearValidationErrors(Wick.ProjectListNote.el.noteForm);
  },
  init() {
    const $noteTextArea = $(Wick.ProjectListNote.el.noteArea);
    if (!$noteTextArea.length) return;

    if (!$(Wick.ProjectListNote.el.loader).length) {
      appendLoader(Wick.ProjectListNote.loaderPayload);
    }

    Wick.ProjectListNote.definedNoteLimit();
    Wick.ProjectListNote.checkInitialValue();
    Wick.ProjectListNote.setHeightForTextarea();
    Wick.ProjectListNote.updateCounterForRemainingCharacters();

    $noteTextArea.on('input', Wick.ProjectListNote.handleNoteInput);
    $(Wick.ProjectListNote.el.btnAddNote).on('click', Wick.ProjectListNote.showEditState);
    $(Wick.ProjectListNote.el.btnSaveNote).on('click', Wick.ProjectListNote.saveNote);
    $(Wick.ProjectListNote.el.btnCloseNote).on('click', Wick.ProjectListNote.closeNote);
    $(Wick.ProjectListNote.el.btnEditNote).on('click', Wick.ProjectListNote.showEditState);
    $(Wick.ProjectListNote.el.btnRemoveNote).on('click', Wick.ProjectListNote.removeNote);
  }
};

$(document).ready(function () {
  Wick.ProjectListNote.init();
});