var Wick = Wick || {};

Wick.InstallerForm = {
  stepSlideDuration: 400,
  stepTransitionDuration: 400,
  steps: [1,2,3],
  PROD_HOSTNAMES: {
    upload_domain: 's3.eu-west-1.amazonaws.com',
    register_url: 'https://installer-registration.external.wickes.co.uk'
  },
  TEST_HOSTNAMES: {
    upload_domain: 's3.eu-west-1.amazonaws.com',
    register_url: 'https://installer-registration.devexternal.wickes.co.uk'
  },
  CUSTOMER_DATA_URL: '/api/installer/application/customer',
  getEnv: function () {
    return window.location.origin.startsWith('https://www.wickes.co.uk') ? 'prod' : 'test';
  },
  getHostnames: function() {
    var env = Wick.InstallerForm.getEnv();
    return env === 'prod'
      ? Wick.InstallerForm.PROD_HOSTNAMES
      : Wick.InstallerForm.TEST_HOSTNAMES;
  },
  filesForm: {
    setValue: function(installerFileName, value) {
      var inputFileRow = $('input.installer_question-file_input[name="' + installerFileName + '"]');

      inputFileRow.attr('data-value', value);
    },
    removeValue: function(installerFileName) {
      var inputFileRow = $('input.installer_question-file_input[name="' + installerFileName + '"]');

      inputFileRow.attr('data-value', '');
      inputFileRow.prop('value', '');
    },
    showAddFileTemplate: function (installerFileName) {
      var addFileTemplate = $('label.installer_question-file_label[data-installer-file-name="' + installerFileName + '"]');

      addFileTemplate.removeClass('hide');
    },
    hideAddFileTemplate: function (installerFileName) {
      var addFileTemplate = $('label.installer_question-file_label[data-installer-file-name="' + installerFileName + '"]');

      addFileTemplate.addClass('hide');
    },
    showErrorNotification: function (installerFileName, error) {
      Wick.InstallerValidation.addErrorNotificationToElement(installerFileName, error, true)
    },
    hideErrorNotification: function (installerFileName) {
      Wick.InstallerValidation.removeErrorNotificationFromElement(installerFileName)
    },
    showDefaultError: function (element) {
      Wick.InstallerValidation.addErrorNotificationToElement(element.attr('name'), Wick.InstallerValidation.steps['2'][element.attr('name')].error, true);
    },
    hideDefaultError: function (element) {
      Wick.InstallerValidation.removeErrorNotificationFromElement(element.attr('name'))
    },
    showImagePreviewTemplate: function (installerFileName) {
      var previewTemplate = $('.installer_question-file_result_wrapper[data-installer-file-name="' + installerFileName + '"]');

      previewTemplate.removeClass('hide');
    },
    hideImagePreviewTemplate: function (installerFileName) {
      var previewTemplate = $('.installer_question-file_result_wrapper[data-installer-file-name="' + installerFileName + '"]');

      previewTemplate.addClass('hide');
    },
    readFile: function (file, installerFileName) {
      var reader = new FileReader();
      var imagePreviewTemplate = $('div.installer_question-file_result_wrapper[data-installer-file-name="' + installerFileName + '"]');

      reader.onload = function(e) {
        var imagePreviewElement = imagePreviewTemplate.find('img');

        imagePreviewElement.attr('src', e.target.result);
      };

      reader.readAsDataURL(file);
    },
    showSpinner: function () {
      var loader = $('.installer__loader');
      loader.addClass('show');
    },
    hideSpinner: function () {
      var loader = $('.installer__loader');
      loader.removeClass('show');
    },
    addFileHandler: function (file, installerFileName) {
      Wick.S3bucketUpload.uploadImage(file, installerFileName);
    },
    onSuccessFileAdd: function (file, installerFileName, fileLink) {
      Wick.InstallerForm.filesForm.hideErrorNotification(installerFileName);
      Wick.InstallerForm.filesForm.hideAddFileTemplate(installerFileName);
      Wick.InstallerForm.filesForm.showImagePreviewTemplate(installerFileName);
      Wick.InstallerForm.filesForm.readFile(file, installerFileName);
      Wick.InstallerForm.filesForm.setValue(installerFileName, fileLink);
    },
    removeFileHandler: function (installerFileName) {
      Wick.InstallerForm.filesForm.hideErrorNotification(installerFileName);
      Wick.InstallerForm.filesForm.removeValue(installerFileName);
      Wick.InstallerForm.filesForm.hideImagePreviewTemplate(installerFileName);
      Wick.InstallerForm.filesForm.showAddFileTemplate(installerFileName);
    },
    fileRadioButtonHandler: function (element) {
      var radioWrapper = element.closest('.installer_question-radio');
      var wrapper = element.closest('.installer_question-wrap');
      if (wrapper.attr('data-question-file') !== undefined) {
        var fileList = wrapper.find('.installer_question-file_list');
        var text = element.siblings('span').text().toUpperCase();
        if (text === 'YES') {
          fileList.removeClass('hide');
          wrapper.find('.form-row__error').remove();
        } else {
          fileList.addClass('hide');
          if (radioWrapper.attr('data-radio-optional') === undefined) {
            Wick.InstallerForm.filesForm.showDefaultError(element);
          }
        }
      }
    }
  },
  bindFileInputs: function () {
    $('body').on('change', '.installer_question-file_input', function() {
      var closestLabel = $(this).closest('.installer_question-file_label');
      var file = $(this).get(0).files[0];
      Wick.InstallerForm.filesForm.hideErrorNotification(closestLabel.attr('data-installer-file-name'));
      Wick.InstallerForm.filesForm.addFileHandler(file, closestLabel.attr('data-installer-file-name'));
    });
  },
  bindDeleteFileButtons: function () {
    $('body').on('click', '.delete_action', function() {
      var closestLabel = $(this).closest('.installer_question-file_wrapper');
      Wick.InstallerForm.filesForm.removeFileHandler(closestLabel.attr('data-installer-file-name'));
    });
  },
  bindFileRadioButtons: function () {
    $('body').on('click', '.installer_question-radio input[type="radio"]', function() {
      Wick.InstallerForm.filesForm.hideDefaultError($(this));
      Wick.InstallerForm.filesForm.fileRadioButtonHandler($(this));
    });
  },
  bindStepSubmitButtons: function () {
    $('body').on('click', '.btn[data-step]', function() {
      var currentStep = $(this).attr('data-step');
      var nextStep = $(this).attr('data-back-action') === undefined ? +currentStep + 1 : +currentStep - 1;
      Wick.InstallerForm.setFormStep(currentStep, nextStep);
    });
  },
  bindBusinessTypeCheckboxes: function () {
    let $formItemCheck = $('.form-row__field-item .checkbox-item'),
        $formItemCheckInput = $('.chb input'),
        $additionalForm = $('.additional-form');

    $formItemCheck.on('change', function () {
      if ($(this).find($formItemCheckInput).prop('checked')) {
        $(this).parent().find($additionalForm).slideDown();
      } else {
        $(this).parent().find($additionalForm).slideUp();
      }
    })
  },
  bindClearForm: function () {
    $(window).bind('beforeunload', function(){
      Wick.InstallerForm.clearFormData();
    });
  },
  scrollToStepHeader: function (step) {
    setTimeout(function () {
      var element = $('.installer-block[data-step="'+ step +'"] .installer-block__header');
      var elementHeight = element.height();
      $([document.documentElement, document.body]).animate({
        scrollTop: element.offset().top - elementHeight
      }, Wick.InstallerForm.stepTransitionDuration);
    }, Wick.InstallerForm.stepSlideDuration + 1)
  },
  moveToStep: function (prevStep, nextStep) {
    $('.installer-action').attr('data-step', nextStep);
    $('.installer-application').attr('data-step', nextStep);
    if (nextStep > prevStep) {
      $('.installer-block[data-step="' + prevStep + '"]').attr('data-step-finished', '');
    }
    Wick.InstallerForm.toggleStep(prevStep);
    Wick.InstallerForm.toggleStep(nextStep);
    Wick.InstallerForm.scrollToStepHeader(nextStep);
  },
  toggleStep: function(step) {
    var content = $('.installer-block[data-step="' + step + '"] .installer__accordion__header').siblings('.installer-block__content');
    content.slideToggle(Wick.InstallerForm.stepSlideDuration);
    content.toggleClass('.installer__accordion_collapsed');
  },
  setFormStep: function (prevStep, nextStep) {
    var isFormValid = true;
    Wick.InstallerValidation.removeGlobalErrorNotification();
    if (Wick.InstallerForm.steps.indexOf(nextStep) !== -1) {
      if (nextStep > prevStep) {
        isFormValid = Wick.InstallerValidation.validateStepForInstallerForm(prevStep);
      }
      if (isFormValid) {
        Wick.InstallerForm.moveToStep(prevStep, nextStep);
      } else {
        $('.installer-block[data-step="' + prevStep + '"]').removeAttr('data-step-finished');
      }
    } else {
      if (nextStep > prevStep) {
        isFormValid = Wick.InstallerValidation.validateInstallerForm();
      }
      if (isFormValid) {
        const submit = Wick.InstallerForm.recaptchaDecorate("submit", Wick.InstallerForm.submit)
        submit();
      }
    }
  },
  clearFormData: function () {
    var inputs = Object.assign(
      Wick.InstallerValidation.steps[1],
      Wick.InstallerValidation.steps[2],
      Wick.InstallerValidation.steps[3]
    );

    return Object
      .keys(inputs)
      .forEach(function (elementName) {
        var element = $('[name="'+ elementName +'"]');
        var type = element.attr("type");

        if (element.prop('tagName') === 'SELECT') {
          element.prop('value', '');
          return;
        }

        switch (type) {
          case 'radio':
          case 'checkbox':
            $('[name="'+ elementName +'"]:checked').prop('checked', false);
            return;
          case 'file':
          default:
            element.prop('value', '');
            element.prop('value', '');
            return;
        }
      })
  },
  gatheringFormData: function () {
    var inputs = Object.assign(
      Wick.InstallerValidation.steps[1],
      Wick.InstallerValidation.steps[2],
      Wick.InstallerValidation.steps[3]
    );

    return Object
      .keys(inputs)
      .reduce(function (prev, elementName) {
        var next = {
          [elementName]: Wick.InstallerValidation.getValueByName(elementName)
        };
        return Object.assign(
          prev,
          next
        )
      }, {})
  },
  formatInstallationTypes: function (unformattedData) {
    var installationtypes = {};

    unformattedData.installationTypes.forEach(function (type) {
      if (type === 'kitchens') {
        installationtypes.kitchens = {
          installationsNumber: unformattedData.installationsNumber_kitchen,
          gasSafeRegistration: unformattedData.gasSafeRegistration,
          hasSolidWorktopsExperience: unformattedData.hasSolidWorktopsExperience,
          canArrangePreviousWorks: unformattedData.canArrangePreviousWorks_kitchen
        };

        if (!!unformattedData.gasSafeCardFront) {
          installationtypes.kitchens.gasSafeCardFront = unformattedData.gasSafeCardFront;
        }

        if (!!unformattedData.gasSafeCardBack) {
          installationtypes.kitchens.gasSafeCardBack = unformattedData.gasSafeCardBack;
        }

        if (!!unformattedData.gasSafeCertificate) {
          installationtypes.kitchens.gasSafeCertificate = unformattedData.gasSafeCertificate;
        }
      }
      if (type === 'bathrooms') {
        installationtypes.bathrooms = {
          installationsNumber: unformattedData.installationsNumber_bathroom,
          canArrangePreviousWorks: unformattedData.canArrangePreviousWorks_bathroom
        };
      }
      if (type === 'flooring') {
        installationtypes.flooring = {
          installationsNumber: unformattedData.installationsNumber_flooring,
          flooringTypes: unformattedData.flooringTypes,
          installers: unformattedData.installers_flooring,
          hasFlooringQualification: unformattedData.hasFlooringQualification,
          canArrangePreviousWorks: unformattedData.canArrangePreviousWorks_flooring
        };
      }
      if (type === 'tiling') {
        installationtypes.tiling = {
          installationsNumber: unformattedData.installationsNumber_tiling,
          tilingTypes: unformattedData.tilingTypes,
          installers: unformattedData.installers_tiling,
          hasTilingQualification: unformattedData.hasTilingQualification,
          canArrangePreviousWorks: unformattedData.canArrangePreviousWorks_tiling
        };
      }
    });

    return installationtypes;
  },
  formatFormData: function (unformattedData) {
    var installerInfo = {
      personalDetails: {
        email: unformattedData.email,
        title: unformattedData.title,
        firstName: unformattedData.firstName,
        lastName: unformattedData.lastName
      },
      businessDetails: {
        businessName: unformattedData.businessName,
        businessType: unformattedData.businessType,
        postCode: unformattedData.postCode,
        line1: unformattedData.line1,
        town: unformattedData.town,
        mobileNumber: unformattedData.mobileNumber
      },
      proofOfInstaller: {
        hasLiabilityInsurance: unformattedData.hasLiabilityInsurance,
        hasPartPCertificate: unformattedData.hasPartPCertificate,
        hasAsbestosAwarenessCertificate: unformattedData.hasAsbestosAwarenessCertificate,
        hasVatCertificate: unformattedData.hasVatCertificate,
      },
      installationTypes: Wick.InstallerForm.formatInstallationTypes(unformattedData),
      additionalInstallationTypes: unformattedData.additionalInstallationTypes,
      preferences: unformattedData.preferences
    };

    if (!!unformattedData.line2) {
      installerInfo.businessDetails.line2 = unformattedData.line2;
    }

    if (!!unformattedData.liabilityInsurance) {
      installerInfo.proofOfInstaller.liabilityInsurance = unformattedData.liabilityInsurance;
    }

    if (!!unformattedData.partPCertificateFront) {
      installerInfo.proofOfInstaller.partPCertificateFront = unformattedData.partPCertificateFront;
    }

    if (!!unformattedData.partPCertificateBack) {
      installerInfo.proofOfInstaller.partPCertificateBack = unformattedData.partPCertificateBack;
    }

    if (!!unformattedData.asbestosAwarenessCertificate) {
      installerInfo.proofOfInstaller.asbestosAwarenessCertificate = unformattedData.asbestosAwarenessCertificate;
    }

    if (unformattedData.hasVatCertificate === 'installer_application_vat_registered_yes' && !!unformattedData.vatCertificate) {
      installerInfo.proofOfInstaller.vatCertificate = unformattedData.vatCertificate;
    }

    if (unformattedData.businessType !== 'sole_trader') {
      if (!!unformattedData.hasCompanyIncorporationCertificate) {
        installerInfo.proofOfInstaller.hasCompanyIncorporationCertificate = unformattedData.hasCompanyIncorporationCertificate;
      }
      if (!!unformattedData.companyIncorporationCertificate) {
        installerInfo.proofOfInstaller.companyIncorporationCertificate = unformattedData.companyIncorporationCertificate;
      }
    }

    if (unformattedData.businessType === 'sole_trader') {
      if (!!unformattedData.hasUtrNumber) {
        installerInfo.proofOfInstaller.hasUtrNumber = unformattedData.hasUtrNumber;
      }
      if (!!unformattedData.utrNumberCopy) {
        installerInfo.proofOfInstaller.utrNumberCopy = unformattedData.utrNumberCopy;
      }
    }

    return installerInfo;
  },
  redirectToThankYouPage: function () {
    window.location.href = './page_installer-thank-you.html';
  },
  handleSubmitSuccess: function () {
    Wick.InstallerForm.filesForm.hideSpinner();
    Wick.InstallerForm.redirectToThankYouPage();
  },
  handleSubmitError: function (error) {
    Wick.InstallerForm.filesForm.hideSpinner();
    if (error.status === 202) {
      Wick.InstallerForm.redirectToThankYouPage();
    }
    if (error.status >= 400 && error.status < 600) {
      Wick.InstallerValidation.addGlobalErrorNotification(3, ['submit']);
    }
  },
  submit: function (recaptchaToken) {
    var hostnames = Wick.InstallerForm.getHostnames();
    var URL_POST_LINK = hostnames.register_url + '/installer';

    var unformatedData = Wick.InstallerForm.gatheringFormData();
    var installerInfo = Wick.InstallerForm.formatFormData(unformatedData);
    installerInfo['g-recaptcha-response'] = recaptchaToken;

    Wick.InstallerForm.filesForm.showSpinner();

    $.ajax({
      type: 'POST',
      url: URL_POST_LINK,
      contentType: 'application/json',
      data: JSON.stringify(installerInfo)
    })
      .done(Wick.InstallerForm.handleSubmitSuccess)
      .fail(Wick.InstallerForm.handleSubmitError);
  },
  retrieveCustomerData: function() {
    const $emailField = $('#email');
    $.ajax({
      type: 'GET',
      url: Wick.InstallerForm.CUSTOMER_DATA_URL,
      success: function(data) {
        Wick.InstallerForm.populateCustomerData(data);
        if ($emailField.val()) {
          $emailField.prop('disabled', true);
        }
      }
    });
  },
  populateCustomerData: function(data) {
    $("#title option").filter(function() {
       return $(this).text().toLowerCase() === data.title.toLowerCase();
    }).prop('selected', true);
    $('#first-name').val(data.firstName);
    $('#surname').val(data.lastName);
    $('#email').val(data.email);
    $('#tel').val(data.phone);
    $('#business-name').val(data.businessName);
    $('#address-line-1').val(data.line1);
    $('#address-line-2').val(data.line2);
    $('#city-town').val(data.town);
    $('#postcode').val(data.postcode);
    $('#Email').prop('checked', data.sendEmail);
    $('#SMS').prop('checked', data.sendSms);
    $('#Phone').prop('checked', data.sendPhone);
    $('#Post').prop('checked', data.sendPost);
  },

  RECAPTCHA_PUBLIC_KEY: '6LdVZ74ZAAAAABiyCm6Szsv5T9wbrOCegkskM2iR',

  recaptchaDecorate: function (action, f) {
    return function() {
      const context = this
      const args = arguments
      grecaptcha.ready(function () {
        grecaptcha.execute(Wick.InstallerForm.RECAPTCHA_PUBLIC_KEY, {
          action: action
        }).then(function (token) {
          f.call(context, token, ...args)
        })
      })
    }
  }
};

$(document).ready(function () {
  Wick.InstallerForm.bindClearForm();
  Wick.InstallerForm.bindFileInputs();
  Wick.InstallerForm.bindDeleteFileButtons();
  Wick.InstallerForm.bindFileRadioButtons();
  Wick.InstallerForm.bindStepSubmitButtons();
  Wick.InstallerForm.bindBusinessTypeCheckboxes();
  Wick.InstallerForm.retrieveCustomerData();
});

// Polyfills
if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}
