'use client'

import clsx from 'clsx'
import { useTranslations } from 'next-intl'
import { useRouter } from 'next/navigation'
import { type ComponentProps } from 'react'

import { TbChevronLeft, TbChevronRight } from 'react-icons/tb'

import { IPaginationOptions } from '@/types'

import { itemStyles, rootStyles } from './Pagination.styles'

import { addParam, getPaginationData, removeParam } from '@/utils'

type PaginationProps = {
	pagination: IPaginationOptions
	getData?: (data: Record<string, any>) => void
} & ComponentProps<'ul'>

function Pagination({
	pagination,
	getData,
	className,
	...props
}: PaginationProps) {
	const t = useTranslations('pagination')
	//
	const router = useRouter()
	//
	const data = getPaginationData(pagination)
	//
	const onPrevPage = () => {
		const page = data.page - 1
		//
		if (page !== 0) {
			addParam(router, 'page', page)
		} else {
			removeParam(router, 'page')
		}
		//
		getData?.({
			page
		})
	}
	//
	const onPage = (page: number) => {
		const newPage = page - 1
		//
		if (newPage !== 0) {
			addParam(router, 'page', newPage)
		} else {
			removeParam(router, 'page')
		}
		//
		getData?.({
			page: newPage
		})
	}
	//
	const onNextPage = () => {
		const page = data.page + 1
		//
		addParam(router, 'page', page)
		//
		getData?.({
			page
		})
	}
	//
	return (
		<ul
			role='navigation'
			aria-label='pagination'
			className={clsx(rootStyles, className)}
			{...props}
		>
			<li>
				<button
					onClick={onPrevPage}
					className={itemStyles({
						isPrevOrNext: true,
						type: 'icon'
					})}
					disabled={!data.hasPrevPage}
				>
					<TbChevronLeft />
					<span>{t('prev')}</span>
				</button>
			</li>
			{data.pageNumbers.map(page => {
				return (
					<li key={page}>
						<button
							onClick={() => {
								if (
									page !== data.page + 1 &&
									page !== 'ellipsis'
								) {
									onPage(page)
								}
							}}
							className={itemStyles({
								isActive: page === data.page + 1,
								isPrevOrNext: page === 'ellipsis'
							})}
							disabled={page === 'ellipsis'}
						>
							{page === 'ellipsis' ? '…' : page}
						</button>
					</li>
				)
			})}
			<li>
				<button
					onClick={onNextPage}
					className={itemStyles({
						isPrevOrNext: true,
						type: 'icon'
					})}
					disabled={!data.hasNextPage}
				>
					<span>{t('next')}</span>
					<TbChevronRight />
				</button>
			</li>
		</ul>
	)
}

export { Pagination }
