// /* global document console */

import ready from 'Utils/documentReady.js';
import getScrollSize from 'Utils/getScrollSize.js';
import Swiper, { Navigation, Pagination, EffectFade, Autoplay  } from 'swiper';
import Chart from 'chart.js/auto'
import flatpickr from 'flatpickr';
import { Russian } from "flatpickr/dist/l10n/ru.js"
import Accordion from 'accordion-js';

Swiper.use([Navigation, Pagination, EffectFade, Autoplay]);

ready(function() {
  document.documentElement.style.setProperty('--css-scroll-size', `${getScrollSize()}px`);

  const containerWidth = document.querySelector('.container').getBoundingClientRect().width;

  flatpickr.localize(flatpickr.l10ns.ru);

  const filterDates = document.querySelectorAll('.fitler__form-date ');

  if (filterDates.length > 0) {
    filterDates.forEach(date => {
      const filterDateStart = date.querySelector('input[name="dateStart"]'),
            filterDateEnd = date.querySelector('input[name="dateEnd"]');

      if (filterDateStart) {
        flatpickr(filterDateStart, {
          disableMobile: "true",
          altInput: true,
          altFormat: "d-m-Y",
          onChange: function(selectedDates, dateStr, instance){
              flatpickrDateEnd.config.minDate = dateStr;
          },
        });

        const flatpickrDateEnd = flatpickr(filterDateEnd, {
          disableMobile: "true",
          altInput: true,
          altFormat: "d-m-Y",
        });
      }
    });
  };

  if (containerWidth >= 766) {
    new Swiper(".top-slider .swiper", {
      // autoplay: false,
      // delay: 2000,
      // disableOnIntenpm raction: false,
      speed: 1000,
      effect: 'fade',
      slidesPerView: 1,
      navigation: {
        prevEl: ".top-slider .swiper-button-prev",
        nextEl: ".top-slider .swiper-button-next",
      },
    });
  }

  const stages = document.querySelectorAll('.stages');

  if (stages.length > 0) {
    stages.forEach(stage => {
      createStage(stage);
    });
  }

  // Генерация этапов по кнопке "Сгенерировать отчёт"
  // const generateReportBtns = document.querySelectorAll('.generate-report');

  // if (generateReportBtns.length > 0) {
  //   generateReportBtns.forEach(btn => {
  //     btn.addEventListener('click', () => {
  //       const stage = btn.closest('.lr-block').querySelector('.lr-block__right .stages');

  //       createStage(stage);
  //     });
  //   });
  // }

  function createStage(stage) {
    let stagesData = stage.dataset.json;

    if (stagesData) {
      stagesData = JSON.parse(stagesData);
      
      stagesData.forEach(({id, name, table, report, chart}) => {
        const tableChartSection = document.createElement('section');
        tableChartSection.id = `table-chart${id}`;
        tableChartSection.className = 'table-chart';
        
        let reportStructure = '';
        if (report) {
          reportStructure = `
            <div class='table-chart__s-second'>
              <div class='btn-group btn-group--right'>
                <a class="btn  btn--ico btn--transparent" href="${report.fileLink}" download="${report.fileName}">
                  <svg width="16" height="16"><use xlink:href="img/sprite.svg#download"></use></svg> Скачать отчёт
                </a>
              </div>
            </div>
          `;
        }

        const tableChartStructure = `
          <div class='table-chart__first'>
            <div class='table-chart__id'>
              <span>ID: ${id}</span>
            </div>
  
            <h6 class='table-chart__name'>${name}</h6>
          </div>
  
          <div class='table-chart__second'>
            <div class='table-chart__s-first'></div>
            ${reportStructure}
          </div>
  
          <div class='table-chart__third'>
            <div id='stage${id}'><canvas id='stage${id}Chart'></canvas></div>
          </div>
        `;
  
        tableChartSection.insertAdjacentHTML('beforeend', tableChartStructure);
        tableChartSection.querySelector('.table-chart__s-first').insertAdjacentElement('beforeend', createTable(table));

        stage.insertAdjacentElement('beforeend', tableChartSection);

        if (chart) {
          createChart(id, chart.type, chart.labels, chart.datasets);
        }
        
      });
    }
  }

  function createTable(tableArr) {
    const table = document.createElement('table');
    table.className = 'table';

    tableArr.forEach((rowArr, i) => {
      const tableRow = document.createElement('tr');

      rowArr.forEach(cell => {
        if (i > 0) {
          tableRow.insertAdjacentHTML('beforeend', `<td>${cell}</td>`);
        } else {
          tableRow.insertAdjacentHTML('beforeend', `<th>${cell}</th>`);
        }
      });

      table.insertAdjacentElement('beforeend', tableRow)
    });

    return table;
  };

  function createChart(id, type, labels, dataset) {
    const legendMargin = {
      id: 'legendMargin',
      beforeInit(chart, legend, options) {
        const fitValue = chart.legend.fit;
  
        chart.legend.fit = function fit() {
          const mrgBottom = containerWidth > 320 ? 20 : 15;
          fitValue.bind(chart.legend)();

          return this.height += mrgBottom;
        }
      }
    };

    const data = {
      labels: labels,
      datasets: dataset,
    }

    console.log(containerWidth);

    const config = {
      type: type,
      data: data,
      options: {
        aspectRatio: containerWidth > 320 ? 2 : 1,
        plugins: {
          legend: {
              maxHeight: 300,
              align: containerWidth > 320 ? 'center' : 'start',
              labels: {
                padding: containerWidth > 766 ? 50 : 15,
              }
          },
        },
        elements: {
          line: {
            tension: 0.2,
          }
        }
      },
      plugins: [legendMargin],
    };
    
    new Chart(
      document.getElementById(`stage${id}Chart`),
      config
    );
  };

  const accordions = Array.from(document.querySelectorAll('.accordion-container'));
  new Accordion(accordions, {
    // openOnInit: [0]
  });


  const editTables = document.querySelectorAll('.edit-table');

  if (editTables.length > 0) {
    editTables.forEach(tableArea => {
      let tableOrigin = '';

      tableArea.addEventListener('click', (e) => {
        console.log('et-edit');

        if (e.target.classList.contains('et-delete')) {
          e.target.closest('tr').remove();
        }

        if (e.target.classList.contains('et-edit')) {
          console.log('et-edit');

          const parent = e.target.closest('.edit-table'),
                editArea = parent.querySelector('.edit'),
                editAreaFirst = editArea.querySelector('.edit__first'),
                editAreaSecond = editArea.querySelector('.edit__second');

          tableOrigin = parent.querySelector('.table').cloneNode(true);

          parent.classList.add('editing');
          editAreaFirst.classList.add('hide');
          editAreaSecond.classList.add('show');
        }

        if (e.target.classList.contains('et-add-cancel')) {
          const parent = e.target.closest('.edit-table');
          const tableArea = parent.querySelector('.table-r');

          tableArea.innerHTML = '';
          tableArea.insertAdjacentElement('beforeend', tableOrigin);

          tableOrigin = parent.querySelector('.table').cloneNode(true);
        }

        if (e.target.classList.contains('et-add-save')) {
          const parent = e.target.closest('.edit-table'),
                editArea = parent.querySelector('.edit'),
                editAreaFirst = editArea.querySelector('.edit__first'),
                editAreaSecond = editArea.querySelector('.edit__second'),
                tableInputs = parent.querySelectorAll('.table .field-text__input');

          parent.classList.remove('editing');
          editAreaFirst.classList.remove('hide');
          editAreaSecond.classList.remove('show');

          tableInputs.forEach(input => {
            const inputTd = input.closest('td');
            inputTd.innerHTML = input.value;
          });
        }

        if (e.target.classList.contains('et-add-row')) {
          const parent = e.target.closest('.edit-table'),
                table = parent.querySelector('.table'),
                tableTrCopy = table.querySelector('tr:last-child').cloneNode(true),
                tableTrCopyTd = tableTrCopy.querySelectorAll('td:not([data-hide])');
              
          console.log(tableTrCopyTd);

          tableTrCopyTd.forEach(td => {
            td.innerHTML = `
              <input class="field-text__input" type="text">
            `;
          });

          table.insertAdjacentElement('beforeend', tableTrCopy);
        }
      });

      tableArea.addEventListener('change', (e) => {
        if (e.target.getAttribute('name') == 'highlight') {
          e.target.closest('tr').classList.toggle('highlight');
        }
      });
    });
  }
  
});

// import $ from 'jquery'; // Перед использованием установить как зависимость
// $(function() {
//   console.log('jQuery героически сработал!');
// });
