import { useClickAway } from "@uidotdev/usehooks";
import React, { type MutableRefObject, useState, type ReactNode } from "react";
import { useTheme } from "../../hooks/useTheme";
import { getBorderRadius } from "../../utils/getBorderRadius";
import { MIcon } from "./MIcon";

export interface SelectItem<T extends string = string> {
	id: T;
	label: string;
}

export const Select = ({
	items,
	activeItem,
	setItem,
	customItem,
}: {
	items: SelectItem[];
	activeItem: SelectItem;
	setItem: (value: string) => void;
	customItem?: ReactNode;
}) => {
	const theme = useTheme();
	const [showOptions, setShowOptions] = useState<boolean>(false);
	const containerRef = useClickAway(() =>
		setShowOptions(false),
	) as MutableRefObject<HTMLDivElement>;

	// biome-ignore format:
	const labelStyle = `bn-text-base bn-font-normal bn-pr-[5px] ${showOptions ? 'bn-text-accent-1' : 'bn-text-secondary'}`

	return (
		<div className="bn-relative bn-w-fit" ref={containerRef}>
			<button
				type="button"
				onClick={() => setShowOptions(!showOptions)}
				className="bn-capitalize bn-border-0 bn-bg-transparent bn-flex bn-items-center bn-p-0 bn-cursor-pointer"
			>
				<span className={labelStyle}>{activeItem.label}</span>
				<MIcon classNames="bn-text-primary" name="keyboard_arrow_down" />
			</button>

			{showOptions && (
				<div
					className="bn-flex bn-flex-col bn-absolute bn-right-0 bn-top-8 bn-bg-layer-2 bn-z-10 bn-w-[100px] bn-max-h-[150px] bn-overflow-y-auto"
					style={{ borderRadius: getBorderRadius(theme.borderRadius, 8) }}
				>
					{items.map((item) => (
						<button
							key={item.id}
							type="button"
							className="bn-bg-transparent bn-text-left bn-text-primary bn-outline-none bn-border-0 bn-text-sm bn-font-normal bn-px-2 bn-py-1.5 bn-capitalize bn-cursor-pointer hover:bn-bg-layer-3"
							onClick={() => {
								setItem(item.id);
								setShowOptions(false);
							}}
						>
							{item.label}
						</button>
					))}
					{customItem}
				</div>
			)}
		</div>
	);
};
