"use client";
import { Button } from "@/components/ui/button";
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import React, { useEffect, useState } from "react";

type PaginationProps = {
	totalPages: number;
	currentPage: number;
	maxVisible?: number;
};

export default function Pagination({
	totalPages,
	currentPage,
	maxVisible = 4,
}: PaginationProps) {
	const searchParams = useSearchParams();
	const activePage = searchParams.get("page") ?? 1;
	const router = useRouter();

	const [queryParams, setQueryParams] = useState<{ [key: string]: string }>({});

	useEffect(() => {
		const params = Object.fromEntries(
			Array.from(searchParams.entries()).filter(([key]) => key !== "page"),
		);
		setQueryParams(params);
	}, [searchParams]);

	useEffect(() => {
		if (!searchParams.has("page")) {
			router.replace(`?page=1${IncludeQueries()}`);
		}
	});

	function IncludeQueries() {
		return Object.entries(queryParams)
			.map(([key, value]) => `&${key}=${value}`)
			.join("");
	}

	const generatePageNumbers = (): (number | string)[] => {
		const halfVisible = Math.floor(maxVisible / 2);
		let startPage = Math.max(currentPage - halfVisible, 1);
		const endPage = Math.min(startPage + maxVisible - 1, totalPages);

		if (endPage - startPage + 1 < maxVisible) {
			startPage = Math.max(endPage - maxVisible + 1, 1);
		}

		const pageNumbers: (number | string)[] = [];

		if (startPage > 1) {
			pageNumbers.push(1);
			if (startPage > 2) pageNumbers.push("...");
		}

		for (let i = startPage; i <= endPage; i++) {
			pageNumbers.push(i);
		}

		if (endPage < totalPages) {
			if (endPage < totalPages - 1) pageNumbers.push("...");
			pageNumbers.push(totalPages);
		}

		return pageNumbers;
	};

	const pageNumbers = generatePageNumbers();

	return (
		<div className="flex items-center justify-center space-x-2 my-4">
			{currentPage > 1 && (
				<Link href={`?page=${Number(currentPage) - 1}${IncludeQueries()}`}>
					<Button variant="secondary" className="flex items-center gap-2">
						<ArrowLeftIcon className="h-4 w-4" />
					</Button>
				</Link>
			)}

			{pageNumbers.map((page) => (
				<React.Fragment key={`${page}`}>
					{typeof page === "number" ? (
						<Link href={`?page=${page}${IncludeQueries()}`}>
							<Button
								variant={Number(activePage) === page ? "default" : "outline"}
							>
								{page}
							</Button>
						</Link>
					) : (
						<span className="px-2">...</span>
					)}
				</React.Fragment>
			))}

			{currentPage < totalPages && (
				<Link href={`?page=${Number(currentPage) + 1}${IncludeQueries()}`}>
					<Button variant="secondary" className="flex items-center gap-2">
						<ArrowRightIcon className="h-4 w-4" />
					</Button>
				</Link>
			)}
		</div>
	);
}
