import paginationInner from "../../../components/pagination-inner.hbs";
import paginationItem from "../../../components/pagination-item.hbs";


const el = {
  paginationInner: '.pagination',
  paginationLink: '.pagination__item a',
  linkActiveClass: 'pagination__link_active',
  paginationItemFocusClass: 'pagination__link--focus',
}

export function paintPagination(payload) {
  const container = $(payload.container);
  const pagesLength = payload.pagesLength;

  container.empty();

  if (pagesLength >= 2) {
    container.append(paginationInner());
    paintPaginationItems(payload);
  }
};

function paintPaginationItems(payload) {
  const currentPage = payload.currentPage;
  const pagesLength = payload.pagesLength;
  const paginationInnerSelector = el.paginationInner;
  const pageNumbersArray = Array.from({length: pagesLength}, (_, index) => index + 1);
  const isPreviousPage = currentPage !== 1;
  const isNextPage = currentPage < pagesLength;
  const isHiddenPages = pagesLength > 5;

  let paginationItems = '';

  if (isPreviousPage) {
    paginationItems += paginationItem({previous: isPreviousPage, pageNumber: currentPage - 1});
  }

  if (isHiddenPages) {
    const truncatedArray = getTruncatedArray(currentPage, pageNumbersArray);
    const arrayWithPasses = getArrayWithPasses(truncatedArray);

    arrayWithPasses.forEach((value) => {
      paginationItems += addPaginationItem(value, currentPage);
    });
  } else {
    pageNumbersArray.forEach((value) => {
      paginationItems += addPaginationItem(value, currentPage);
    });
  }

  if (isNextPage) {
    paginationItems += paginationItem({next: isNextPage, pageNumber: currentPage + 1});
  }

  $(paginationInnerSelector).append(paginationItems);
};

function getTruncatedArray(currentNumber, numberArray) {
  const truncatedArray = [];
  const currentIndex = numberArray.indexOf(currentNumber);
  const prevIndex = numberArray.indexOf(currentNumber - 1);
  const nextIndex = numberArray.indexOf(currentNumber + 1);
  const numberArrayLength = numberArray.length - 1;
  const requiredNumbersAmount = 5;

  let uniqueTruncatedArray = [];

  if (currentIndex !== -1) {
    if (currentIndex !== 0) {
      truncatedArray.push(numberArray[0]);
    }

    if (currentIndex > 0) {
      truncatedArray.push(numberArray[prevIndex])
    }

    truncatedArray.push(numberArray[currentIndex]);

    if (currentIndex < numberArrayLength) {
      truncatedArray.push(numberArray[nextIndex]);
    }

    if (currentIndex !== numberArrayLength) {
      truncatedArray.push(numberArray.at(-1));
    }
  }

  uniqueTruncatedArray = [...new Set(truncatedArray)];
  if (uniqueTruncatedArray.length < requiredNumbersAmount) {
    let insertItemBefore = currentIndex === numberArrayLength || nextIndex === numberArrayLength
    uniqueTruncatedArray = [...addMissedItem(uniqueTruncatedArray, currentNumber, insertItemBefore)]
  }

  return uniqueTruncatedArray;
}

function addMissedItem(arr, currentNumber, insertItemBefore) {
  const requiredNumbersAmount = 5;
  const arrLength = arr.length;
  const missedItemsAmount = requiredNumbersAmount - arrLength;
  const updatedArray = [...arr];

  for (let i = 0; i < missedItemsAmount; i++) {
    let valueToInsert = insertItemBefore
      ? currentNumber - i - 2
      : currentNumber + i + 2;

    updatedArray.push(valueToInsert);
  }

  updatedArray.sort(function (a, b) {
    return a - b;
  });

  return updatedArray;

}

function getArrayWithPasses(arr) {
  return arr.reduce((result, num, index, newArray) => {
    result.push(num);

    if (index < newArray.length - 1 && newArray[index + 1] !== num + 1) {
      result.push(0);
    }

    return result;
  }, []);
}
function addPaginationItem(pageValue, currentPage) {
  const isPageActive = pageValue === currentPage;
  const isHidden = pageValue === 0;

  if(isHidden) {
    return paginationItem({hidden: isHidden});
  }

  return paginationItem({item: true, hidden: isHidden, currentPage: isPageActive, pageNumber: pageValue});
}


function callPaginationEvent(context, callback) {
  const numberAttr = 'data-page-number';

  if(!$(context).hasClass(el.linkActiveClass)) {
    const pageNumber = Number($(context).attr(numberAttr));
    callback(pageNumber);
  }
}

export function removePaginationFocus() {
  $(el.paginationLink).removeClass(el.paginationItemFocusClass);
}

function addPaginationItemFocus(element) {
  $(element).addClass(el.paginationItemFocusClass);
}

export function addPaginationEvent(container, callback) {
  $(container).on('click', el.paginationLink, (e) => {
    e.preventDefault();
    addPaginationItemFocus(e.currentTarget)
    callPaginationEvent(e.currentTarget, callback);
  });
}
