import React from 'react';

const Pagination = ({ currentPage, totalPages, onPageChange }) => {
    const handlePageClick = (e, page) => {
        if (e) {
            e.preventDefault();
        }

        if (page !== currentPage && page >= 1 && page <= totalPages) {
            onPageChange(page);
            // Scroll to top of blog section smoothly
            const blogSection = document.querySelector('.blog-section');
            if (blogSection) {
                const offset = 100; // Offset from top
                const elementPosition = blogSection.getBoundingClientRect().top;
                const offsetPosition = elementPosition + window.pageYOffset - offset;

                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });
            }
        }
    };

    const renderPageNumbers = () => {
        const pages = [];
        const maxVisiblePages = 5;

        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        if (endPage - startPage < maxVisiblePages - 1) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        for (let i = startPage; i <= endPage; i++) {
            pages.push(
                <button
                    key={i}
                    type="button"
                    className={`pagination-number ${currentPage === i ? 'active' : ''}`}
                    onClick={(e) => handlePageClick(e, i)}
                >
                    {i}
                </button>
            );
        }

        return pages;
    };

    return (
        <div className="pagination-wrapper">
            <div className="pagination-container">
                {/* Previous Button */}
                <button
                    type="button"
                    className="pagination-arrow pagination-arrow-prev"
                    onClick={(e) => handlePageClick(e, currentPage - 1)}
                    disabled={currentPage === 1}
                >
                    «
                </button>

                {/* Page Numbers */}
                {renderPageNumbers()}

                {/* Next Button */}
                <button
                    type="button"
                    className="pagination-arrow pagination-arrow-next"
                    onClick={(e) => handlePageClick(e, currentPage + 1)}
                    disabled={currentPage === totalPages}
                >
                    »
                </button>
            </div>
        </div>
    );
};

export default Pagination;
