"use client";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useState, useTransition } from "react";

interface FilterOption {
	value: string;
	label: string;
	icon: React.ReactNode;
}

interface FilterProps {
	options: FilterOption[];
	defaultOption: string;
	queryParamKey: string;
}

export default function Filter({
	options,
	defaultOption,
	queryParamKey,
}: FilterProps) {
	const [selectedOption, setSelectedOption] = useState(defaultOption);
	const searchParams = useSearchParams();
	const { replace } = useRouter();
	const pathname = usePathname();
	const [isPending, startTransition] = useTransition();

	function handleFilterChange(value: string) {
		setSelectedOption(value);
		const params = new URLSearchParams(searchParams.toString());

		params.set(queryParamKey, value);
		params.set("page", "1");

		startTransition(() => {
			replace(`${pathname}?${params.toString()}`);
		});
	}

	return (
		<div className={cn(isPending && "animate-pulse")}>
			<Select
				disabled={isPending}
				value={selectedOption}
				onValueChange={(val) => handleFilterChange(val)}
			>
				<SelectTrigger className="w-auto bg-white">
					<SelectValue>
						{options.find((option) => option.value === selectedOption)?.label}
					</SelectValue>
				</SelectTrigger>
				<SelectContent align="end">
					{options.map((option) => (
						<SelectItem key={option.value} value={option.value}>
							<div className="flex items-center gap-4">
								{option.icon}
								<span>{option.label}</span>
							</div>
						</SelectItem>
					))}
				</SelectContent>
			</Select>
		</div>
	);
}
