import React, { useEffect, useState } from 'react' import type { PaginationEventType, PaginationProps } from './pagination' import Button from '../Button/Button.tsx' import { classNames } from '../../utils/classNames' import ChevronLeft from '../../icons/chevron-left.svg?raw' import ChevronRight from '../../icons/chevron-right.svg?raw' import styles from './pagination.module.scss' export type Props = PaginationProps & { onChange?: (event: PaginationEventType) => void } const Pagination = ({ type, showChevrons, showDots, disablePrevious, disableNext, previousLink, nextLink, previousPageLabel = 'Previous', nextPageLabel = 'Next', pages, theme = 'outline', totalPages, currentPage, onChange, className // eslint-disable-next-line complexity }: Props) => { const [calculatedCurrentPage, setCalculatedCurrentPage] = useState( currentPage || (pages?.findIndex(page => page.active) || -1) + 1 || 1 ) const classes = classNames([ styles.pagination, theme !== 'outline' && (theme === null || theme === undefined ? styles.primary : styles[theme]), type === 'dots' && styles.dots, className ]) const calculatedTotalPages = totalPages || pages?.length || 0 const generatedPages = pages?.length ? pages : Array(totalPages || 0).fill(0).map((_, index) => ({ ...(index === 0 && { active: true }), label: index + 1 })) const paginate = (to: string | number) => { const previousPage = calculatedCurrentPage let currentPage = calculatedCurrentPage if (to === 'prev') { currentPage = calculatedCurrentPage - 1 } else if (to === 'next') { currentPage = calculatedCurrentPage + 1 } else { currentPage = to as number } const label = pages?.[currentPage - 1]?.label setCalculatedCurrentPage(currentPage) onChange?.({ page: currentPage, direction: previousPage > currentPage ? 'prev' : 'next', ...(label && { label }) }) } useEffect(() => { if (currentPage) { setCalculatedCurrentPage(currentPage) } }, [currentPage]) return ( ) } export default Pagination