type PaginationProps = {
    currentPage: number;
    totalPages: number;
    onPageChange: (page: number) => void;
};

const Pagination = ({ currentPage, totalPages, onPageChange }: PaginationProps) => {
    const generatePages = () => {
        const pages: (number | 'dots')[] = [];

        if (totalPages <= 7) {
            for (let i = 1; i <= totalPages; i++) pages.push(i);
        } else {
            pages.push(1);

            if (currentPage > 3) pages.push('dots');

            const startPage = Math.max(2, currentPage - 1);
            const endPage = Math.min(totalPages - 1, currentPage + 1);

            for (let i = startPage; i <= endPage; i++) {
                if (!pages.includes(i)) {
                    pages.push(i);
                }
            }

            if (currentPage < totalPages - 2) pages.push('dots');

            if (!pages.includes(totalPages)) {
                pages.push(totalPages);
            }
        }

        return pages;
    };

    return (
        <div className="flex justify-center items-center gap-2 mt-6">
            <button
                onClick={() => onPageChange(currentPage - 1)}
                disabled={currentPage === 1}
                className="w-9 h-9 rounded-full  text-gray-500 disabled:opacity-50 flex items-center justify-center"
            >
                &lt;
            </button>

            {generatePages().map((page, index) => {
                if (page === 'dots') {
                    return (
                        <span
                            key={`dots-${index}`}
                            className="w-9 h-9 rounded-full  text-gray-500 flex items-center justify-center"
                        >
                            ...
                        </span>
                    );
                }

                return (
                    <button
                        key={`page-${page}`}
                        onClick={() => onPageChange(page)}
                        className={`w-9 h-9 rounded-full  text-sm flex items-center justify-center transition
                            ${currentPage === page
                                ? 'bg-primary-500 text-white'
                                : 'text-gray-800 hover:bg-gray-100'
                            }`}
                    >
                        {page}
                    </button>
                );
            })}

            <button
                onClick={() => onPageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
                className="w-9 h-9 rounded-full  text-gray-500 disabled:opacity-50 flex items-center justify-center"
            >
                &gt;
            </button>
        </div>
    );
};

export default Pagination;
