'use client'

export function Pagination({ totalPages, currentPage, fileId, callBack }: any) {

	if (totalPages === 0) {
		return null;
	}

	const getVisiblePages = () => {
		const pages = [];
		const maxVisible = 7;
		let start = Math.max(1, currentPage - 3);
		let end = Math.min(totalPages, currentPage + 3);

		if (end - start + 1 < maxVisible) {
			if (start === 1) {
				end = Math.min(totalPages, start + maxVisible - 1);
			} else if (end === totalPages) {
				start = Math.max(1, end - maxVisible + 1);
			}
		}

		for (let i = start; i <= end; i++) {
			pages.push(i);
		}

		return pages;
	};

	const visiblePages = getVisiblePages();

	return (
		<div className="pagination-wrapper">
			{visiblePages[0] > 1 && (
				<>
					<button
						className={`pagination-button`}
						onClick={() => callBack(fileId, 1, true)}
					>
						1
					</button>
					{visiblePages[0] > 2 && <span>...</span>}
				</>
			)}

			{visiblePages.map(page => (
				<button
					key={page}
					onClick={() => callBack(fileId, page, true)}
					className={`pagination-button ${page === currentPage ? 'current-page' : ''}`}
				>
					{page}
				</button>
			))}

			{visiblePages[visiblePages.length - 1] < totalPages && (
				<>
					{visiblePages[visiblePages.length - 1] < totalPages - 1 && <span>...</span>}
					<button
						className={`pagination-button`}
						onClick={() => callBack(fileId, totalPages, true)}
					>
						{totalPages}
					</button>
				</>
			)}
		</div>
	);
}