"use client"

import type { IPaginationProps } from "./Pagination.d"
import type { JSX } from "react"

import { Flex, IconButton, Text } from "@radix-ui/themes"
import {
	ChevronLeft,
	ChevronRight,
	ChevronsLeft,
	ChevronsRight,
} from "lucide-react"
import { forwardRef, useMemo } from "react"

export const Pagination = forwardRef<HTMLDivElement, IPaginationProps>(
	(
		{ currentPage, totalPages, onPageChange, showFirstLast = true, ...props },
		ref,
	): JSX.Element => {
		const pages = useMemo(() => {
			const items: (number | "ellipsis")[] = []
			const maxVisible = 5

			if (totalPages <= maxVisible) {
				for (let i = 1; i <= totalPages; i++) items.push(i)
			} else {
				items.push(1)
				if (currentPage > 3) items.push("ellipsis")

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

				for (let i = start; i <= end; i++) items.push(i)

				if (currentPage < totalPages - 2) items.push("ellipsis")
				items.push(totalPages)
			}

			return items
		}, [currentPage, totalPages])

		return (
			<Flex
				ref={ref}
				role="navigation"
				align="center"
				gap="1"
				aria-label="Пагинация"
				{...props}
			>
				{showFirstLast && (
					<IconButton
						variant="soft"
						size="1"
						onClick={() => onPageChange(1)}
						disabled={currentPage === 1}
						aria-label="Первая страница"
					>
						<ChevronsLeft size={16} />
					</IconButton>
				)}
				<IconButton
					variant="soft"
					size="1"
					onClick={() => onPageChange(currentPage - 1)}
					disabled={currentPage === 1}
					aria-label="Предыдущая страница"
				>
					<ChevronLeft size={16} />
				</IconButton>

				{pages.map((page, index) =>
					page === "ellipsis" ? (
						<Text key={`ellipsis-${index}`} size="2" color="gray" mx="1">
							...
						</Text>
					) : (
						<IconButton
							key={page}
							variant={page === currentPage ? "solid" : "soft"}
							size="1"
							onClick={() => onPageChange(page)}
							aria-current={page === currentPage ? "page" : undefined}
						>
							{page}
						</IconButton>
					),
				)}

				<IconButton
					variant="soft"
					size="1"
					onClick={() => onPageChange(currentPage + 1)}
					disabled={currentPage === totalPages}
					aria-label="Следующая страница"
				>
					<ChevronRight size={16} />
				</IconButton>
				{showFirstLast && (
					<IconButton
						variant="soft"
						size="1"
						onClick={() => onPageChange(totalPages)}
						disabled={currentPage === totalPages}
						aria-label="Последняя страница"
					>
						<ChevronsRight size={16} />
					</IconButton>
				)}
			</Flex>
		)
	},
)

Pagination.displayName = "Pagination"
