import { useEffect, useRef } from "react";
import type { SlashCommand } from "../../types/commands";
import { slashCommandSourceLabel } from "../../utils/slashCommands";
import styles from "./SlashCommandMenu.module.css";

interface SlashCommandMenuProps {
	commands: SlashCommand[];
	selectedIndex: number;
	onSelect: (command: SlashCommand) => void;
}

export function SlashCommandMenu({ commands, selectedIndex, onSelect }: SlashCommandMenuProps) {
	const listRef = useRef<HTMLDivElement>(null);

	useEffect(() => {
		const list = listRef.current;
		if (!list) return;
		const item = list.children[selectedIndex] as HTMLElement | undefined;
		item?.scrollIntoView({ block: "nearest" });
	}, [selectedIndex, commands.length]);

	if (!commands.length) return null;

	return (
		<div className={styles.menu} role="listbox" aria-label="斜杠命令">
			<div ref={listRef} className={styles.list}>
				{commands.map((command, index) => (
					<button
						key={command.name}
						type="button"
						className={`${styles.item} ${index === selectedIndex ? styles.itemActive : ""}`}
						role="option"
						aria-selected={index === selectedIndex}
						onMouseDown={(e) => {
							e.preventDefault();
							onSelect(command);
						}}
					>
						<span className={styles.name}>/{command.name}</span>
						{command.description ? (
							<span className={styles.description}>{command.description}</span>
						) : null}
						<span className={styles.source}>{slashCommandSourceLabel(command.source)}</span>
					</button>
				))}
			</div>
		</div>
	);
}
