import {getPaletteColor} from '../../../assets/js/palette-colors.js';

$( document ).ready(function() {
  var token = $('body').data('token');
  var info  = $('[data-home-info]').data('home-info');


    function getCustomersOnline(){
    $.ajax({
        url: 'index.php?route=common/home/updateDashboard&token=' + token,
        // type: 'get',
    })
    .done(function(json){
      $('.js-total-order').html(json['total_order']);
      $('.js-total-order-year').html(json['total_order_year']);

      $('.js-total-sale').html(json['total_sale']);
      $('.js-total-sale-year').html(json['total_sale_year']);

      $('.js-average-sale').html(json['average_sale']);
      $('.js-text-last-12-months').html(json['text_last_12_months']);

      $('.js-total-product').html(json['total_product']);
      $('.js-total-product-year').html(json['total_product_year']);

      $('.js-total-customer').html(json['total_customer']);
      $('.js-total-customer-year').text(json['total_customer_year']);

      $('.js-customer-online').html(json['total_customer_online']);
      $('.js-customers-online-last-refresh').html(json['customers_online_last_refresh']);
    })
    .fail(function() {

      // notificationMsg('Erro ao recarregar as informações.', 'error');
    })
  }

  $('#refresh-users-online').on('click', function(e){
      // e.preventDefault();
      // e.stopPropagation();     
      getCustomersOnline();
  });


  $('body').on('change', '.js-status-proccess', function() {
    var url = 'index.php?route=common/home/last_sales_order&token=' + token;
    var proccess_status = $(this).val();
    if (proccess_status != '*') {
        url += '&proccess_status=' + encodeURIComponent(proccess_status);
    }

    document.getElementById('loading').classList.remove('hidden');

    $.ajax({
      url: url,
      type: 'get',
      dataType: 'html',
    })
    .done(function(html) {
      var $html = $('<div>').html(html);
      var $cards = $html.find('.js-sales-order-cards');
      var $noCardsMessage = $html.find('.no-cards-message');
      var $viewAllBtn = $html.find('.js-view-all-btn');

      if ($cards.length > 0) {
        $('.js-sales-order-cards').replaceWith($cards);
        $('.no-cards-message').replaceWith($noCardsMessage);

        if ($cards.children().length === 0) {
          $('.no-cards-message').removeClass('hidden');
          $('.js-view-all-btn').addClass('hidden');
        } else {
          $('.no-cards-message').addClass('hidden');
          $('.js-view-all-btn').removeClass('hidden');
        }
      } else {
        $('.js-sales-order-cards').empty();
        $('.no-cards-message').removeClass('hidden');
        $('.js-view-all-btn').addClass('hidden');
      }
    })
    .fail(function() {
      // console.log("error");
    })
    .always(function() {
      document.getElementById('loading').classList.add('hidden');
      // console.log("complete");
    });
  });


  // ======== INICIO 4 GRAFICOS ========
  var chartType = 'line'; 

  function reRenderCharts(range) {
    getSalesChart(range); 
    getSalesChartMarketplace(range); 
    getSalesChartSalesChannel(range); 
    getSalesChartDevice(range); 
  }

  $('#TypeLine').on('change', function() {
    if ($(this).is(':checked')) {
      chartType = 'line'; 
      $('#TypeBar').prop('checked', false); 
      
      let range = $('input[name=range]:checked').val(); 
      reRenderCharts(range);
    }
  });

  $('#TypeBar').on('change', function() {
    if ($(this).is(':checked')) {
      chartType = 'bar'; 
      $('#TypeLine').prop('checked', false); 
      
      let range = $('input[name=range]:checked').val(); 
      reRenderCharts(range); 
    }
  });

  $('input[name=range]').on('change', function(event) {
    event.preventDefault();
    let range = $(this).val(); 
    reRenderCharts(range); 
  });

  let defaultRange = $('input[name=range]:checked').val() || 'month';
  reRenderCharts(defaultRange); 

  // SALES CHART
  function getSalesChart(range) {
    var chartType = $('input[name="chartType"]:checked').val(); 

    $.ajax({
      url: 'index.php?route=common/home/chart&token=' + token + '&range=' + range, 
      type: 'get',
      dataType: 'json',
      async: false
    })
    .done(function(json) {
      $('#myChart').remove();
      $('.js-my-chart').append('<canvas id="myChart" width="400" height="220"></canvas>');
      var ctx = document.getElementById("myChart"),
      myChart = new Chart(ctx, {
      type: chartType, 
      data: {
        labels: json.xaxis,
        datasets: [{
          label: json['label_order'],
          backgroundColor: "rgba(42,110,160,0.2)",
          borderColor: "rgba(42,110,160,1)",
          pointBackgroundColor: "rgba(42,110,160,1)",
          pointBorderColor: "#fff",
          pointHoverBackgroundColor: "#fff",
          pointHoverBorderColor: "rgba(42,110,160,1)",
          data: json.order
          }]
        },
        options: {
          elements: {
            line: {
              tension: 0 // disables bezier curves
            }
          },
          legend: {
            position: 'bottom'
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        },
      });
    })
    .fail(function() {
        // console.log("Erro ao carregar o gráfico.");
    })
    .always(function() {
      // console.log("complete");
    });
  }

  // SALES DEVICE
  function getSalesChartDevice(range) {
    var chartType = $('input[name="chartType"]:checked').val(); 

    $.ajax({
      url : 'index.php?route=common/home/chartDevice&token=' + token + '&range=' + range,
      type: 'get',
      dataType: 'json',
      async: false
    })
    .done(function(json) {
      $('#myChartDevice').remove();
      $('.js-my-chart-device').append('<canvas id="myChartDevice" width="400" height="220"></canvas>');
      var
      ctx = document.getElementById("myChartDevice"),
      myChart = new Chart(ctx, {
        type: chartType,
        data: {
          labels: json.xaxis,
          datasets: [{
            label: json['label_desktop'],
            backgroundColor: "rgba(42,110,160,0.2)",
            borderColor: "rgba(42,110,160,1)",
            pointBackgroundColor: "rgba(42,110,160,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(42,110,160,1)",
            data: json.desktop
          }, {
            label: json['label_tablet'],
            backgroundColor: "rgba(245,131,39,0.2)",
            borderColor: "rgba(245,131,39,1)",
            pointBackgroundColor: "rgba(245,131,39,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(245,131,39,1)",
            data: json.tablet
          }, {
            label: json['label_mobile'],
            backgroundColor: "rgba(50,131,39,0.2)",
            borderColor: "rgba(50,131,39,1)",
            pointBackgroundColor: "rgba(50,131,39,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(50,131,39,1)",
            data: json.mobile
          }]
        },
        options: {
          elements: {
            line: {
              tension: 0 // disables bezier curves
            }
          },
          legend: {
            position: 'bottom'
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      });
    })
    .fail(function() { 
      // console.log(error);
    })
    .always(function() {
      // console.log("complete");
    });
  }

  // SALES MARKETPLACE
  function getSalesChartMarketplace(range) {
    var chartType = $('input[name="chartType"]:checked').val();

    if (info.marketplace_status == "") {
      return false;
    }

    $.ajax({
      url: 'index.php?route=common/home/chartMarketplace&token=' + token + '&range=' + range,
      type: 'get',
      dataType: 'json',
      async: false
    })
    .done(function(json) {
      $('#myChartMarketplace').remove();
      $('.js-my-chart-marketplace').append('<canvas id="myChartMarketplace" width="400" height="220"></canvas>');

      var dataArray = [];

      for (var x=1; x < Object.keys(json).length; x++) {
        dataArray.push({
          label: json[x].label,
          backgroundColor: getPaletteColor(x, 0.2),
          borderColor: getPaletteColor(x),
          pointBackgroundColor: getPaletteColor(x),
          pointBorderColor: "#fff",
          pointHoverBackgroundColor: "#fff",
          pointHoverBorderColor: getPaletteColor(x),
          data: json[x].data
        })
      }

      var
      ctx = document.getElementById("myChartMarketplace"),
      myChart = new Chart(ctx, {
      type: chartType,
      data: {
        labels: json.xaxis,
        datasets: dataArray
      },
      options: {
        elements: {
          line: {
            tension: 0 // disables bezier curves
          }
        },
        legend: {
          position: 'bottom'
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      },
      });
    })
    .fail(function(xhr, status, error, json) {
      console.log(xhr.responseText);
      console.log(status);
      console.log(error);
    })
    .always(function() {
        // console.log("complete");
    });
  }

  // SALES CHANNEL
  function getSalesChartSalesChannel(range) {
    var chartType = $('input[name="chartType"]:checked').val();

    if (info.marketplace_status == "" && info.app_status == 0) {
        return false;
    }

    $.ajax({
    url: 'index.php?route=common/home/chartSalesChannel&token=' + token + '&range=' + range,
    type: 'get',
    dataType: 'json',
    async: false
    })
    .done(function(json) {
      $('#myChartSalesChannel').remove();
      $('.js-my-chart-sales-channel').append('<canvas id="myChartSalesChannel" width="400" height="220"></canvas>');

      var dataArray = [];

      for (var x=1; x < Object.keys(json).length; x++) {
        dataArray.push({
          label: json[x].label,
          backgroundColor: getPaletteColor(x, 0.2),
          borderColor: getPaletteColor(x),
          pointBackgroundColor: getPaletteColor(x),
          pointBorderColor: "#fff",
          pointHoverBackgroundColor: "#fff",
          pointHoverBorderColor: getPaletteColor(x) ,
          data: json[x].data
        })
      }

      var
      ctx = document.getElementById("myChartSalesChannel"),
      myChart = new Chart(ctx, {
        type: chartType, 
        data: {
          labels: json.xaxis,
          datasets: dataArray
        },
        options: {
          elements: {
            line: {
              tension: 0 // disables bezier curves
            }
          },
          legend: {
            position: 'bottom'
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        },
      });
    })
    .fail(function(xhr, status, error, json) {
      console.log(xhr.responseText);
      console.log(status);
      console.log(error);
    })
    .always(function() {
      // console.log("complete");
    });
  }


  // ======== INICIO NOVO GRAFICO ======== 
  $.datepicker.regional['pt-BR'] = {
    closeText: 'Fechar',
    prevText: 'Anterior',
    nextText: 'Próximo',
    currentText: 'Hoje',
    monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
    monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
    dayNames: ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
    dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
    dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
    weekHeader: 'Sm',
    dateFormat: 'dd/mm/yy',
    firstDay: 0,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: ''
  };

  $.datepicker.setDefaults($.datepicker.regional['pt-BR']);

  $('.date-picker').datepicker({
    dateFormat: 'dd/mm/yy',
    changeMonth: false,
    changeYear: false,
    showAnim: 'slideDown'
  });

  function formatDateToDDMMYYYY(dateString) {
    const [year, month, day] = dateString.split('-');
    return `${day}/${month}/${year}`;
  }

  $('input[name="range"]').on('change', function() {
    var selectedValue = $(this).val();
    var errorMsg = $('#date-range-error');
    var errorNoResults = $('#no-results');

    if (selectedValue === 'customizable') {
      const today = new Date();
      const startDate = new Date(today);
      startDate.setDate(today.getDate() - 30); 

      const formattedStartDate = $.datepicker.formatDate('dd/mm/yy', startDate);
      const formattedEndDate = $.datepicker.formatDate('dd/mm/yy', today);

      $('#from').val(formattedStartDate);
      $('#to').val(formattedEndDate); 
      
      $('.customizable-checkbox-container').slideDown(800, 'linear');
      $('#customizable-date-container').slideDown(800, 'linear');
      $('#custom-chart-container').fadeIn(800, 'linear');
      $('.checkbox-container').slideUp(800, 'linear');
      $('.existing-chart-container').slideUp(800, 'linear');

      // chama a funçao para renderizar o grafico após definir as datas
      updateChart();
    } else {      
      $('.checkbox-container').slideDown(800, 'linear');
      $('.existing-chart-container').slideDown(800, 'linear');
      $('.customizable-checkbox-container').slideUp(800, 'linear');
      $('#custom-chart-container').fadeOut(800, 'linear');
      $('#customizable-date-container').slideUp(800, 'linear');
      
      errorMsg.hide();
      errorNoResults.hide();

      getSalesChart(selectedValue);
      getSalesChartDevice(selectedValue);
      getSalesChartMarketplace(selectedValue);
      getSalesChartSalesChannel(selectedValue);
    }
  });

  function validateDateRange() {
    var startDate = $('#from').val();
    var endDate = $('#to').val();
    var errorMsg = $('#date-range-error');
    var errorNoResults = $('#no-results');
    var newGraphic = $('#custom-chart-container');

    var dateFormat = 'dd/mm/yy'; 

    if (startDate && endDate) {
      var startDateObj = $.datepicker.parseDate(dateFormat, startDate);
      var endDateObj = $.datepicker.parseDate(dateFormat, endDate);

      var diffDays = (endDateObj - startDateObj) / (1000 * 60 * 60 * 24);

      if (diffDays > 60) {
        errorMsg.fadeIn(500); 
        errorNoResults.fadeIn(500);
        newGraphic.fadeOut(500);
      } else {
        errorMsg.fadeOut(500); 
        errorNoResults.fadeOut(500);
        newGraphic.fadeIn(500);
      }
    }
  }

  var chartTypeNew = 'line';

  function updateChart() {
    var startDate = $('#from').val();
    var endDate = $('#to').val();
    var errorMsg = $('#date-range-error');
    var errorNoResults = $('#no-results');
    var newGraphic = $('#custom-chart-container');

    if (startDate && endDate) {
      var startDateObj = $.datepicker.parseDate("dd/mm/yy", startDate);
      var endDateObj = $.datepicker.parseDate("dd/mm/yy", endDate);
      var diffDays = (endDateObj - startDateObj) / (1000 * 60 * 60 * 24);

      if (diffDays > 60) {
        errorMsg.fadeIn(500); 
        errorNoResults.fadeIn(500); 
        newGraphic.fadeOut(500);
        return; 
      } else {
        errorMsg.fadeOut(500);
        errorNoResults.fadeOut(500); 
        newGraphic.fadeIn(500);
      }
      fetchChartData(startDate, endDate);
    }
  }
    
  // executa a validaçao quando as datas sao alteradas
  $('#from, #to').on('change', function() {
    validateDateRange();
    updateChart();
  });

  function fetchChartData(startDate, endDate) {
    $.ajax({
      url: `index.php?route=common/home/chartCustom&token=${token}&start_date=${startDate}&end_date=${endDate}`,
      type: 'GET',
      dataType: 'json',
      success: function(response) {
        // console.log(response);
        if (response && response.xaxis && response.order) {
          renderChart(response);
        } else {
          console.error('Dados insuficientes para renderizar o gráfico.');
        }
      },
      error: function(error) {
        console.error('Erro ao buscar os dados:', error);
      }
    });
  }
    
  function renderChart(json) {
    $('#customChart').remove();
    $('.js-my-chart-custom').append('<canvas id="customChart" width="800" height="220"></canvas>');

    var ctx = document.getElementById('customChart');
    var formattedLabels = json.xaxis.map(function(date) {
      return formatDateToDDMMYYYY(date);
    });

    new Chart(ctx, {
      type: chartTypeNew,
      data: {
        labels: formattedLabels,
        datasets: [{
          label: json['label_custom'],
          backgroundColor: "rgba(42,110,160,0.2)",
          borderColor: "rgba(42,110,160,1)",
          pointBackgroundColor: "rgba(42,110,160,1)",
          pointBorderColor: "#fff",
          pointHoverBackgroundColor: "#fff",
          pointHoverBorderColor: "rgba(42,110,160,1)",
          data: json.order,
          tension: 0,
        }]
      },
      options: {
        elements: {
          line: {
            tension: 0 
          }
        },
        legend: {
          position: 'bottom'
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true,
            }
          }]
        }
      }
    });
  }
    
  $('#chartTypeLine').on('change', function() {
    if ($(this).is(':checked')) {
      chartTypeNew = 'line';
      $('#chartTypeBar').prop('checked', false); 
      updateChart();
    }
  });

  $('#chartTypeBar').on('change', function() {
    if ($(this).is(':checked')) {
      chartTypeNew = 'bar';
      $('#chartTypeLine').prop('checked', false); 
      updateChart();
    }
  });


  function easyconfigure() {
    $.ajax({
      url: 'index.php?route=extension/easyconfigure&token=' + token,
      type: 'post',
      dataType: 'html',
    })
    .done(function(json) {
      $('body').append(json);
    })
    .fail(function(json) {
      console.log("error");
    });
  }

  // Configuração rápida
  if ($('.js-quick-config').length > 0) {
    easyconfigure();
  }
  $('.js-setup').on('click', function(event) { // Configbar
    event.preventDefault();
    easyconfigure();
  });

  $('.ads-banner').on('click', '.js-ads-close', function(event) {
    event.preventDefault();
    $('.js-ads-close-confirm').removeClass('hidden');
  });
  $('.ads-banner').on('click', '.js-ads-cancel', function(event) {
    event.preventDefault();
    $('.js-ads-close-confirm').addClass('hidden');
  });

  $('.ads-banner').on('click', '.js-ads-remove', function(event) {

    var data = {};
        data['promotion_id'] = (typeof $('.js-ads-remove').data('promotion-id') != "undefined") ? $('.js-ads-remove').data('promotion-id') : false ;

    $.ajax({
      url: 'index.php?route=common/adsbanner/remove&token=' + token,
			type: 'post',
      data: data,
      dataType: 'json',
      beforeSend:function(){
        $('.js-ads-remove').addClass('btn-loading').attr('disabled', true);
      },
      complete:function(){
        $('.js-ads-remove').removeClass('btn-loading').attr('disabled', false);
      }
    }).done(function(json) {
      if(json['success']){
        location.reload();
      }
    });

    event.preventDefault();
  });

  $.ajax({
    url: 'index.php?route=common/adsbanner&token=' + token,
    dataType:'html'
  }).done(function(html) {
    if(html){
      $('.ads-banner').append(html);
    }
  });
  
});