"use client";

import React from "react";
import { ChevronDown } from "lucide-react";

import {
	SEARCH_LIMITS,
	DEFAULT_SEARCH_LIMIT,
} from "@/lib/frontend/search/urlState";

import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import {
	DropdownMenu,
	DropdownMenuContent,
	DropdownMenuLabel,
	DropdownMenuRadioGroup,
	DropdownMenuRadioItem,
	DropdownMenuSeparator,
	DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

export default function SearchLimitSelect({
	limit,
	onLimitChange,
	isSubmitting,
}) {
	const normalizedLimit =
		Number.isInteger(limit) && SEARCH_LIMITS.includes(limit)
			? limit
			: DEFAULT_SEARCH_LIMIT;

	return (
		<div className="grid gap-2">
			<Label>Treffer pro Seite</Label>

			<DropdownMenu>
				<DropdownMenuTrigger asChild>
					<Button
						type="button"
						variant="outline"
						disabled={isSubmitting}
						title="Treffer pro Seite auswählen"
					>
						{normalizedLimit}
						<ChevronDown className="h-4 w-4" />
					</Button>
				</DropdownMenuTrigger>

				<DropdownMenuContent align="start" className="min-w-48">
					<DropdownMenuLabel>Treffer pro Seite</DropdownMenuLabel>
					<DropdownMenuSeparator />

					<DropdownMenuRadioGroup
						value={String(normalizedLimit)}
						onValueChange={(value) => {
							const n = Number(value);
							if (!Number.isInteger(n)) return;
							onLimitChange(n);
						}}
					>
						{SEARCH_LIMITS.map((n) => (
							<DropdownMenuRadioItem key={n} value={String(n)}>
								{n}
							</DropdownMenuRadioItem>
						))}
					</DropdownMenuRadioGroup>
				</DropdownMenuContent>
			</DropdownMenu>
		</div>
	);
}
