import { Select } from "antd";
import type { SelectProps } from "antd";
import React from "react";

/**
 * 支援滑鼠滾輪切換選項的 Select（參考 quickopen 的滾輪行為）
 * 滑鼠懸停在選單上滾動即可上下切換選項，不需展開下拉
 */
const WheelSelect = (props: SelectProps & { wrapperStyle?: React.CSSProperties }) => {
	const { value, options, onChange, disabled, wrapperStyle, ...rest } = props;

	function handleWheel(e: React.WheelEvent<HTMLDivElement>): void {
		if (disabled || !options || options.length === 0) {
			return;
		}
		const idx: number = options.findIndex((o) => o.value === value);
		const next: number = e.deltaY > 0
			? Math.min(idx + 1, options.length - 1)
			: Math.max(idx - 1, 0);
		if (next !== idx && options[next]) {
			onChange && onChange(options[next].value, options[next]);
		}
	}

	return (
		<div onWheel={handleWheel} style={wrapperStyle}>
			<Select value={value} options={options} onChange={onChange} disabled={disabled} {...rest} />
		</div>
	);
};

export default WheelSelect;
