const navigateButtons = ['first', 'prev', 'next', 'last'];
const listPolp = document.querySelectorAll('.fr-table tbody tr');
const maxPerPage = 20;
const maxRange = 6;
const numberOfPages = Math.ceil(listPolp.length / maxPerPage);
let currentPage = 1;

// Base navigation
const createNavigation = () => {
	const nav = document.createElement('nav');
	const paginationList = document.createElement('ul');
	nav.setAttribute('role', 'navigation');
	nav.className = 'fr-pagination';
	nav.setAttribute('aria-label', 'Pagination tableau');
	paginationList.className = 'fr-pagination__list';

	navigateButtons.map((button) => {
		let navButton = createNavButton(button, true);
		paginationList.appendChild(navButton);
	});

	return { nav, paginationList };
};

// Template button
const createNavButton = (index, isNavigate = false) => {
	const container = document.createElement('li');
	const button = document.createElement('a');
	button.className = 'fr-pagination__link';

	if (isNavigate) {
		button.classList.add(`fr-pagination__link--${index}`);
		if (index === 'prev' || index === 'next')
			button.classList.add('fr-pagination__link--lg-label');
		switch (index) {
			case 'first':
				button.innerHTML = 'Première page';
				break;
			case 'prev':
				button.innerHTML = 'Page précédente';
				break;
			case 'next':
				button.innerHTML = 'Page suivante';
				break;
			default:
				button.innerHTML = 'Dernière page';
				break;
		}
	} else {
		button.innerHTML = '…';
		button.setAttribute('title', `Page ${index}`);
		if (index > 0) {
			button.setAttribute('href', '#');
			button.innerHTML = index;
		}
		// Responsive (hidden on lg screens)
		if (index > 3 && index < numberOfPages - 1) {
			button.classList.add('fr-displayed-lg');
		}
	}

	container.appendChild(button);
	return container;
};

// Set truncations indicators (pagination length limits)
const setTruncats = () => {
	const paginationList = document.querySelector(
		'nav[aria-label="Pagination tableau"] .fr-pagination__list'
	);

	const truncats = paginationList.querySelectorAll('[title="Page 0"]');
	if (truncats.length === 0) {
		const links = paginationList.querySelectorAll('li');
		const limit = Math.ceil(maxRange / 2);
		const truncatMiddle = createNavButton(0);
		const truncatLeft = createNavButton(0);
		const truncatRight = createNavButton(0);

		truncatLeft.setAttribute('style', 'display: none');
		paginationList.querySelector(`:nth-child(3)`).after(truncatLeft);
		truncatMiddle.setAttribute('style', 'display: none');
		paginationList
			.querySelector(`:nth-child(${limit + 3})`)
			.after(truncatMiddle);
		truncatRight.setAttribute('style', 'display: none');
		paginationList
			.querySelector(`:nth-child(${links.length - 1})`)
			.after(truncatRight);
	}
};

// Initialization
const init = () => {
	const table = document.querySelector('table');
	const navContainer = document.createElement('div');
	navContainer.className = 'fr-m-1w';
	navContainer.setAttribute('style', 'text-align:center');
	const { nav, paginationList } = createNavigation();
	for (let i = 1; i <= numberOfPages; i++) {
		let prevButton = paginationList.querySelector(`:nth-child(${i + 1})`);
		let pageButton = createNavButton(i);
		prevButton.after(pageButton);
	}
	nav.appendChild(paginationList);
	navContainer.appendChild(nav);
	table.after(navContainer);
	setCurrentPage(1);
};

// Update buttons display
const updatePagination = () => {
	setTruncats();
	const links = document.querySelectorAll('.fr-pagination__list li');
	const limit = Math.ceil(maxRange / 2);
	truncats = document.querySelectorAll('[title="Page 0"]');
	const [truncatLeft, truncatMiddle, truncatRight] = truncats;

	if (numberOfPages > maxRange + 1) {
		if (currentPage < limit || currentPage > numberOfPages - (limit - 1)) {
			links.forEach((link, index) => {
				if (index < limit + 3 || index > links.length - (limit + 4)) {
					link.removeAttribute('style');
				} else {
					link.setAttribute('style', 'display: none');
				}
				truncatLeft.parentNode.setAttribute('style', 'display:none');
				truncatMiddle.parentNode.removeAttribute('style');
				truncatRight.parentNode.setAttribute('style', 'display:none');
			});
		}
		if (currentPage === limit) {
			links.forEach((link, index) => {
				if (index < currentPage + (limit + 3) || index >= links.length - 3) {
					link.removeAttribute('style');
				} else {
					link.setAttribute('style', 'display: none');
				}
				truncatLeft.parentNode.setAttribute('style', 'display:none');
				truncatMiddle.parentNode.setAttribute('style', 'display:none');
				truncatRight.parentNode.removeAttribute('style');
			});
		}
		if (currentPage > limit && currentPage < numberOfPages - (limit - 1)) {
			links.forEach((link, index) => {
				if (index > 2 && index < links.length - 3) {
					if (
						(index < 6 && index >= currentPage + 1) ||
						(index >= 6 && index >= currentPage + 2 && index <= currentPage + 4)
					) {
						link.removeAttribute('style');
					} else {
						link.setAttribute('style', 'display: none');
					}
				}
				truncatLeft.parentNode.removeAttribute('style');
				truncatMiddle.parentNode.setAttribute('style', 'display:none');
				truncatRight.parentNode.removeAttribute('style');
			});
		}
		if (currentPage === numberOfPages - (limit - 1)) {
			links.forEach((link, index) => {
				if (index < 3 || index > links.length - (limit + 6)) {
					link.removeAttribute('style');
				} else {
					link.setAttribute('style', 'display: none');
				}
				truncatLeft.parentNode.removeAttribute('style');
				truncatMiddle.parentNode.setAttribute('style', 'display:none');
				truncatRight.parentNode.setAttribute('style', 'display:none');
			});
		}
	}
};

// Change page
const setCurrentPage = (index) => {
	currentPage = index;
	// Navigation
	updatePagination();
	const prevCurrentButton = document.querySelector('[aria-current="page"]');
	if (prevCurrentButton) prevCurrentButton.removeAttribute('aria-current');
	const newCurrentButton = document.querySelector(
		`[title="Page ${currentPage}"]`
	);
	newCurrentButton.setAttribute('aria-current', 'page');
	handleNavigate();

	// Table items
	const prevRange = (currentPage - 1) * maxPerPage;
	const currRange = currentPage * maxPerPage;

	listPolp.forEach((polp, index) => {
		polp.style.display = 'none';
		if (index >= prevRange && index < currRange) {
			polp.style.display = '';
		}
	});
};

// Change navigate buttons states
const disableButtons = (buttons) => {
	buttons.forEach((button) => {
		button.setAttribute('aria-disabled', 'true');
		button.setAttribute('role', 'link');
		button.removeAttribute('href');
	});
};

const enableButtons = (buttons) => {
	buttons.forEach((button) => {
		button.removeAttribute('aria-disabled');
		button.removeAttribute('role');
		button.setAttribute('href', '#');
	});
};

const handleNavigate = () => {
	const firstButton = document.querySelector(
		'nav[aria-label="Pagination tableau"] .fr-pagination__link--first'
	);
	const prevButton = document.querySelector(
		'nav[aria-label="Pagination tableau"] .fr-pagination__link--prev'
	);
	const nextButton = document.querySelector(
		'nav[aria-label="Pagination tableau"] .fr-pagination__link--next'
	);
	const lastButton = document.querySelector(
		'nav[aria-label="Pagination tableau"] .fr-pagination__link--last'
	);
	if (currentPage === 1) {
		disableButtons([firstButton, prevButton]);
	} else {
		enableButtons([firstButton, prevButton]);
	}
	if (currentPage === numberOfPages) {
		disableButtons([lastButton, nextButton]);
	} else {
		enableButtons([lastButton, nextButton]);
	}
};

window.addEventListener('load', () => {
	if (numberOfPages > 1) {
		init();

		const links = document.querySelectorAll(
			'nav[aria-label="Pagination tableau"] .fr-pagination__link'
		);
		links.forEach((link, index) => {
			link.addEventListener('click', () => {
				if (currentPage > 1 && index <= 1) {
					setCurrentPage(index === 0 ? 1 : currentPage - 1);
				}
				if (currentPage < numberOfPages && index >= links.length - 2) {
					setCurrentPage(
						index === links.length - 1 ? numberOfPages : currentPage + 1
					);
				}
				if (link.getAttribute('title')) {
					const indexButton = parseInt(
						link.getAttribute('title').split(' ')[1]
					);
					setCurrentPage(indexButton);
				}
			});
		});
	}
});
