"use client";

import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { type FC, type ReactNode } from "react";
import clsx from "clsx";
import { cn } from "@/lib/utils";

interface DropdownOption {
	name: string;
	icon?: ReactNode;
	onClick: () => void;
	className?: string;
}

interface DropdownProps {
	children: ReactNode;
	options: DropdownOption[];
	isOpen: boolean;
	onToggle: () => void;
	classNameContent?: string;
	classNameTrigger?: string;
}

const Dropdown: FC<DropdownProps> = ({
	children,
	options = [],
	isOpen,
	onToggle,
	classNameContent = "",
	classNameTrigger = "",
}) => {
	return (
		<DropdownMenu.Root open={isOpen} onOpenChange={onToggle}>
			<DropdownMenu.Trigger asChild>
				<button
					type="button"
					className={clsx(
						"inline-flex items-center focus:outline-none",
						classNameTrigger,
					)}
					aria-haspopup="true"
					aria-expanded={isOpen}
				>
					{children}
				</button>
			</DropdownMenu.Trigger>

			<DropdownMenu.Portal>
				<DropdownMenu.Content
					className={clsx(
						"z-50 overflow-hidden p-2 bg-white border border-fill-150 rounded-[16px] min-w-[130px]",
						classNameContent,
					)}
					side="bottom"
					align="start"
					style={{ boxShadow: "0px 4px 10px 0px #00000014" }}
					sideOffset={8}
				>
					{options.map((option, index) => (
						<DropdownMenu.Item
							key={`${option.name}-${index}`}
							onSelect={(e) => {
								e.preventDefault();
								option.onClick();
							}}
							className={cn(
								"focus:outline-none flex items-center gap-2 h-8 px-2 text-sm text-text-light-900 hover:bg-fill-100 cursor-pointer rounded-[8px] transition-colors",
								option.className,
							)}
						>
							{option.icon && (
								<span className="w-4 h-4 flex items-center justify-center text-inherit">
									{option.icon}
								</span>
							)}
							<span>{option.name}</span>
						</DropdownMenu.Item>
					))}
				</DropdownMenu.Content>
			</DropdownMenu.Portal>
		</DropdownMenu.Root>
	);
};

export { Dropdown };
