import {
  isValidEmail,
  isValidOrderNumber,
  isValidPhoneNumber,
  isValidTitle, removeErrorStyling,
  updateStylingError
} from "./utils/validation";

var Wick = window.Wick || {};

Wick.TrackMyOrder = {
  el: {
    $trackMyOrder: $('.track-order'),
    $tabOptionsInputs: $('input[name="track-order-options"]'),
    $trackOrderForm: $('.track-order-form'),
    $trackOrderMainSection: $('.track-order__main'),
    formRow: '.track-order-form .form-row',
    formRowOptionsInput: '.track-order-form .tab-content input',
    orderInput: '#order',
    telInput: '#tel',
    emailInput: '#email',
    postcodeInput: '#postcode',
    formInvalidClass: 'form_invalid',
    notification: '.notification',
    fieldError: '.form-row.form-row_validation-error',
    tabContentActive: '.tab-content .tab-pane.active',
    options: '.tab-content',
    $myOrderSection: $('.my-order'),
    btnPrint: '.btn--print',
    tooltip: '.icon-info-component',
  },
  errorMessages: {
    errorOrderNumber: 'Please enter a valid order number',
    errorTel: 'Please enter a valid phone number',
    errorPostcode: 'Please enter a valid billing postcode',
    errorEmail: 'Please enter a valid email address',
  },
  getFieldsConfigurations: function () {
    return [
      {
        input: Wick.TrackMyOrder.el.orderInput,
        validator: isValidOrderNumber,
        error: Wick.TrackMyOrder.errorMessages.errorOrderNumber
      },
      {
        input: Wick.TrackMyOrder.el.telInput,
        validator: isValidPhoneNumber,
        error: Wick.TrackMyOrder.errorMessages.errorTel
      },
      {
        input: Wick.TrackMyOrder.el.postcodeInput,
        validator: isValidTitle,
        error: Wick.TrackMyOrder.errorMessages.errorPostcode
      },
      {
        input: Wick.TrackMyOrder.el.emailInput,
        validator: isValidEmail,
        error: Wick.TrackMyOrder.errorMessages.errorEmail
      }
    ]
  },
  validateInput: function (input, validatorFunction, errorMsg) {
    const trimmedValue = $(input).val().trim();
    $(input).val(trimmedValue);

    const isValid = validatorFunction(trimmedValue);
    updateStylingError(input, isValid, errorMsg);

    return isValid;
  },
  validateForm: function() {
    let isValid = true;

    const alwaysActiveFields = $(Wick.TrackMyOrder.el.orderInput);
    isValid = Wick.TrackMyOrder.validateInput(alwaysActiveFields, isValidOrderNumber, Wick.TrackMyOrder.errorMessages.errorOrderNumber) && isValid;

    const activeField = $(Wick.TrackMyOrder.el.tabContentActive).find('input');

    if (isValid && activeField.length) {
      const fieldConfig = Wick.TrackMyOrder.getFieldsConfigurations().find(
        (field) => field.input === `#${activeField.attr("id")}`
      );

      if (fieldConfig) {
        isValid = Wick.TrackMyOrder.validateInput(fieldConfig.input, fieldConfig.validator, fieldConfig.error) && isValid;
      }
    }

    return isValid;
  },
  resetTabContentFieldInputs () {
    const getAllInputs = $(Wick.TrackMyOrder.el.formRowOptionsInput);

    getAllInputs.each(function () {
      $(this).val('');
    });
  },
  bindTabOptionsClick() {
    Wick.TrackMyOrder.el.$tabOptionsInputs.click(function () {
      $(this).tab('show');
      $(this).removeClass('active');

      const getErrorElementOptions = $(Wick.TrackMyOrder.el.options).find(Wick.TrackMyOrder.el.fieldError)

      if (getErrorElementOptions.length) {
        removeErrorStyling(getErrorElementOptions);
      }

      Wick.TrackMyOrder.resetTabContentFieldInputs();
    });
  },
  handleTrackOrderFormSubmit() {
    Wick.TrackMyOrder.el.$trackOrderForm.on('submit', function (event) {
      event.preventDefault();

      if (Wick.TrackMyOrder.validateForm()) {
        event.target.submit();
      }
    });
  },
  scrollToElement($element) {
    if ($element.length) {
      $('html, body').animate({
        scrollTop: $element.offset().top - 20
      }, 300);
    }
  },
  handleScrollBehaviorOnLoad() {
    const $formFieldWithError = $(Wick.TrackMyOrder.el.fieldError);

    if ($formFieldWithError.length) {
      Wick.TrackMyOrder.scrollToElement(Wick.TrackMyOrder.el.$trackOrderMainSection);
    } else if (Wick.TrackMyOrder.el.$myOrderSection.length) {
      Wick.TrackMyOrder.scrollToElement(Wick.TrackMyOrder.el.$myOrderSection);
    }
  },
  handlePrint() {
    $(Wick.TrackMyOrder.el.btnPrint).click((e) => {
      e.preventDefault();
      console.log("Print button clicked");
      window.print();
    })
  },
  handleTooltip() {
    $(Wick.TrackMyOrder.el.tooltip).on("click", function (event) {
      event.preventDefault();
      event.stopPropagation();
    });
  },
  init() {
    Wick.TrackMyOrder.handleScrollBehaviorOnLoad();
    Wick.TrackMyOrder.handleTrackOrderFormSubmit();
    Wick.TrackMyOrder.bindTabOptionsClick();
    Wick.TrackMyOrder.handlePrint();
    Wick.TrackMyOrder.handleTooltip();
  }
}

$(document).ready(function () {
  if (!Wick.TrackMyOrder.el.$trackMyOrder.length) {
    return;
  }

  Wick.TrackMyOrder.init();
});
