import React from "react";

export default function Pagination({ activePage, handlePageClick, totalPages }) {
	const getPages = () => {
		const pages = [];
		const delta = 2;

		const rangeStart = Math.max(2, activePage - delta);
		const rangeEnd = Math.min(totalPages - 1, activePage + delta);

		pages.push(1);

		if (rangeStart > 2) {
			pages.push("...");
		}

		for (let i = rangeStart; i <= rangeEnd; i++) {
			pages.push(i);
		}

		if (rangeEnd < totalPages - 1) {
			pages.push("...");
		}

		if (totalPages > 1) {
			pages.push(totalPages);
		}

		return pages;
	};

	const pages = getPages();

	return (
		<>
			{/* Previous */}
			<li className={activePage === 1 ? "disabled" : ""}>
				<a
					onClick={() => activePage > 1 && handlePageClick(activePage - 1)}
					className='pagination-link animate-hover-btn'>
					<span className='icon icon-arrow-left' />
				</a>
			</li>

			{pages.map((page, index) =>
				page === "..." ? (
					<li key={`dots-${index}`} className='pagination-dots'>
						<span>...</span>
					</li>
				) : (
					<li key={page} className={activePage === page ? "active" : ""}>
						<a className='pagination-link animate-hover-btn' onClick={() => handlePageClick(page)}>
							{page}
						</a>
					</li>
				),
			)}

			{/* Next */}
			<li className={activePage === totalPages ? "disabled" : ""}>
				<a
					onClick={() => activePage < totalPages && handlePageClick(activePage + 1)}
					className='pagination-link animate-hover-btn'>
					<span className='icon icon-arrow-right' />
				</a>
			</li>
		</>
	);
}
