'use client'

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

	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>
			<div style={{ display: 'flex', gap: '5px', marginTop: '10px' }}>
				{/* Кнопка первой страницы */}
				{visiblePages[0] > 1 && (
					<>
						<button onClick={() => callBack(fileId, 1)}>1</button>
						{visiblePages[0] > 2 && <span>...</span>}
					</>
				)}

				{/* Видимые страницы */}
				{visiblePages.map(page => (
					<button
						key={page}
						onClick={() => callBack(fileId, page)}
						style={{
							padding: '5px 10px',
							border: '1px solid #ddd',
							background: currentPage === page ? '#007bff' : 'white',
							color: currentPage === page ? 'white' : 'black',
							cursor: 'pointer',
							fontWeight: currentPage === page ? 'bold' : 'normal'
						}}
					>
						{page}
					</button>
				))}

				{/* Кнопка последней страницы */}
				{visiblePages[visiblePages.length - 1] < totalPages && (
					<>
						{visiblePages[visiblePages.length - 1] < totalPages - 1 && <span>...</span>}
						<button onClick={() => callBack(fileId, totalPages)}>{totalPages}</button>
					</>
				)}
			</div>
		</div>
	);
}