import { type FC } from 'react';
import {
    Pagination,
    PaginationContent,
    PaginationItem,
    PaginationLink,
    PaginationEllipsis,
} from './ui/pagination';
import { type PagerType } from '../pages/products/types/Types';

interface PaginationUiProps {
    pager: PagerType | null | undefined;
    onPageChange: (page: number) => void;
}

const PaginationUi: FC<PaginationUiProps> = ({ pager, onPageChange }) => {
    const handlePageChange = (page: number) => {
        onPageChange(page);
    };

    const getPageNumbers = () => {
        if (!pager) return [];

        const pageNumbers: (number | 'ellipsis')[] = [];
        const maxVisiblePages = 5;

        if (pager.totalPages <= maxVisiblePages) {
            for (let i = 1; i <= pager.totalPages; i++) {
                pageNumbers.push(i);
            }
        } else {
            const startPage = Math.max(1, pager.page - 2);
            const endPage = Math.min(pager.totalPages, pager.page + 2);

            // اگر صفحه شروع > 1 باشد، 1 و ellipsis اضافه کن
            if (startPage > 1) {
                pageNumbers.push(1);
                if (startPage > 2) {
                    pageNumbers.push('ellipsis');
                }
            }

            // صفحات میانی
            for (let i = startPage; i <= endPage; i++) {
                pageNumbers.push(i);
            }

            // اگر صفحه پایان < totalPages باشد، ellipsis و صفحه آخر اضافه کن
            if (endPage < pager.totalPages) {
                if (endPage < pager.totalPages - 1) {
                    pageNumbers.push('ellipsis');
                }
                pageNumbers.push(pager.totalPages);
            }
        }

        return pageNumbers;
    };

    if (!pager || pager.totalPages <= 1) {
        return null;
    }

    return (
        <div className="flex justify-center mt-6">
            <Pagination>
                <PaginationContent>
                    {getPageNumbers().map((page, index) => (
                        <PaginationItem key={index}>
                            {page === 'ellipsis' ? (
                                <PaginationEllipsis />
                            ) : (
                                <PaginationLink
                                    href="#"
                                    isActive={page === pager.page}
                                    onClick={(e) => {
                                        e.preventDefault();
                                        handlePageChange(page);
                                    }}
                                >
                                    {page}
                                </PaginationLink>
                            )}
                        </PaginationItem>
                    ))}
                </PaginationContent>
            </Pagination>
        </div>
    );
};

export default PaginationUi;
