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 {
            if (pager.page > 3) {
                pageNumbers.push(1);
                if (pager.page > 4) {
                    pageNumbers.push('ellipsis');
                }
            }

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

            for (let i = start; i <= end; i++) {
                pageNumbers.push(i);
            }

            if (pager.page < pager.totalPages - 2) {
                if (pager.page < pager.totalPages - 3) {
                    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;
