window.waitEvent('scripts_document', function() {
  if ($('#checkout-cart-data').length && $('#checkout-cart-data').data('checkout-cart')) {
    var data = JSON.parse($('#checkout-cart-data').data('checkout-cart')),
      action = data.action,
      shippingMethod = data.shipping_method,
      button_shipping = data.button_shipping;
  }

  function displayResult(html) {
    $('#postcode-result')
      .removeClass('hidden')
      .html(html);

    window.dispatchEvent(new CustomEvent('quote-shipping'));
  }

  function renderText(shipping_method) {
    var html = '';

    for (var i in shipping_method) {
      if (!shipping_method[i].error) {
        var QUOTE = shipping_method[i].quote;

        for (var j in QUOTE) {
          html += '<div class="flex nowrap-xs between-xs middle-xs vertical-padding-x-small">';
          html += '<span class="text-medium text-gray">' + QUOTE[j].title + '</span>';
          html += '<span class="text-medium text-dark text-bold text-nowrap">' + QUOTE[j].text + '</span>';
          html += '</div>';
        }
      }
    }

    displayResult(html);
  }

  function renderInput(shipping_method) {
    var html = '';
    html += ' <form action="' + action + '" method="post">';

    for (var i in shipping_method) {
      if (!shipping_method[i].error) {
        var QUOTE = shipping_method[i].quote;

        for (var j in QUOTE) {
          var CODE = QUOTE[j].code,
            CHECKED = CODE == shippingMethod ? 'checked="checked"' : '';

          html += '<label class="radio radio-small">';
          html +=
            '<input type="radio" name="shipping_method" class="radio-entry" value="' +
            CODE +
            '" id="' +
            CODE +
            '" ' +
            CHECKED +
            '>';
          html += '<div class="radio-text flex nowrap-xs between-xs middle-xs">';
          html += '<span class="text-medium text-gray right-padding-x-small">' + QUOTE[j].title + '</span>';
          html +=
            '<span class="text-medium text-dark text-bold ' +
            (CODE == 'futura_frete_conta_cliente.futura_frete_conta_cliente' ? '' : 'text-nowrap') +
            ' left-padding-x-small">' +
            QUOTE[j].text +
            '</span>';
          html += '</div>';
          html += '</label>';
        }
      } else {
        html += '<span class="text-error text-small">' + shipping_method[i].error + '</span>';
      }
    }

    var DISABLED = shippingMethod ? '' : 'disabled="disabled"';

    html +=
      '<button type="submit" id="button-shipping" class="btn-default btn-medium btn-full top-margin-medium" ' +
      DISABLED +
      '>';
    html += ' <span>' + button_shipping + '</span>';
    html += '</button>';

    html += ' </form>';

    displayResult(html);
  }

  function initQuoteShipping(postcode_button, postcode_input, type, qty_input) {
    type = type || 'text';

    postcode_input.keyup(function(event) {
      if (event.keyCode == '13' || $(this).val().length === 9) {
        postcode_button.trigger('click');
      }
    });

    postcode_button.on('click', function(e) {
      e.preventDefault();

      var $data = {};

      $data.cep = encodeURIComponent(postcode_input.val());
      $data.postcode = $data.cep;
      $data.freteproduto_id = postcode_input.data('product-id');
      $data.qty = typeof qty_input !== 'undefined' ? qty_input.val() : 1;

      $.ajax({
        url: 'index.php?route=checkout/cart/quoteShipping',
        type: 'POST',
        dataType: 'json',
        data: $data,
        beforeSend: function() {
          postcode_button.prop('disabled', true);
          postcode_button.addClass('btn-loading');
        },
        complete: function() {
          postcode_button.prop('disabled', false);
          postcode_button.removeClass('btn-loading');
        },
        success: function(json) {
          $('.success, .warning, .attention, .error').remove();
          if (json.error) {
            if (json.error.warning) {
              window.notificationMsg(json.error.warning, 'warning');
            }

            if (json.error.postcode) {
              postcode_input.addClass('field-entry-error');
              var html =
                '<span class="visible-block text-small text-error js-postcode-error">' +
                json.error.postcode +
                '</span>';
              displayResult(html);
            }
          }

          if (json.shipping_method) {
            if (type == 'radio') {
              renderInput(json.shipping_method);
            } else {
              renderText(json.shipping_method, json);
            }

            $('input[name="shipping_method"]').bind('change', function() {
              $('#button-shipping').prop('disabled', false);
            });
          }
        },
        error: function(error) {
          console.log(error);
        },
      });
    });
  }

  window.initQuoteShipping = initQuoteShipping;
});
