import { useEffect, useState } from 'react';
import { __ } from '@wordpress/i18n';
import { HiArrowLeft, HiArrowRight } from 'react-icons/hi';

function range(start, end) {
	return Array.from({ length: Math.max(0, end - start + 1) }, (_, i) => start + i);
}

function getPages(totalPages, currentPage, siblingCount = 1) {
	// show all pages if the count is small (no ellipses)
	if (totalPages <= 7) return range(1, totalPages);

	const pages = [];
	const push = (x) => {
		if (pages[pages.length - 1] !== x) pages.push(x);
	};

	push(1);

	const start = Math.max(2, currentPage - siblingCount);
	const end = Math.min(totalPages - 1, currentPage + siblingCount);

	if (start > 2) push('...');
	for (let i = start; i <= end; i++) push(i);
	if (end < totalPages - 1) push('...');

	push(totalPages);
	return pages;
}

const Pagination = ({
	totalItems,
	itemsPerPage,
	onPageChange,
	siblingCount = 1,
	currentPage: controlledPage, // optional controlled prop
}) => {
	const totalPages = Math.max(1, Math.ceil(totalItems / itemsPerPage));
	const [page, setPage] = useState(controlledPage ?? 1);

	useEffect(() => {
		if (controlledPage != null) setPage(controlledPage);
	}, [controlledPage]);

	const go = (p) => {
		const next = Math.min(Math.max(1, p), totalPages);
		if (next === page) return;
		if (controlledPage == null) setPage(next);
		onPageChange?.(next);
	};

	const items = getPages(totalPages, page, siblingCount);

	return (
		<div className='edbi-shortcodes__pagination'>
			<button
				onClick={() => go(page - 1)}
				disabled={page === 1}
				className='edbi-pagination__button'
			>
				<HiArrowLeft />
				{__('Prev', 'easy-dropbox-integration')}
			</button>

			{items.map((it, idx) =>
				it === '...' ? (
					<span key={`dots-${idx}`}>…</span>
				) : (
					<button
						key={`p-${it}`}
						onClick={() => go(it)}
						aria-current={it === page ? 'page' : undefined}
						className={`edbi-pagination__page__button ${
							it === page
								? 'edbi-pagination__button--active'
								: 'edbi-pagination__button--inactive'
						}`}
					>
						{it}
					</button>
				)
			)}

			<button
				onClick={() => go(page + 1)}
				disabled={page === totalPages}
				className='edbi-pagination__button'
			>
				{__('Next', 'easy-dropbox-integration')}
				<HiArrowRight />
			</button>
		</div>
	);
};

export default Pagination;
