'use client';

import React, { useRef, useEffect, useState } from 'react';
import { useAtom, useSetAtom, useAtomValue } from 'jotai';
import {
	commandLineStateAtom,
	updateSearchQueryAtom,
	selectCommandAtom,
	commandHistoryAtom,
	selectedSuggestionIndexAtom,
} from '../../commands/store';
import { commandRegistry } from '../../commands/registry';

/**
 * CommandSearch
 *
 * Autocomplete search input for finding commands.
 * Shows suggestions as user types.
 */
export function CommandSearch() {
	const [state] = useAtom(commandLineStateAtom);
	const updateSearchQuery = useSetAtom(updateSearchQueryAtom);
	const selectCommand = useSetAtom(selectCommandAtom);
	const history = useAtomValue(commandHistoryAtom);
	const [selectedIndex, setSelectedIndex] = useAtom(selectedSuggestionIndexAtom);

	const inputRef = useRef<HTMLInputElement>(null);
	const [inputValue, setInputValue] = useState('');

	// Focus input on mount
	useEffect(() => {
		inputRef.current?.focus();
	}, []);

	// Get current suggestions
	const suggestions = state.phase === 'searching' ? state.suggestions : commandRegistry.all();

	// Handle input change
	const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const value = e.target.value;
		setInputValue(value);
		updateSearchQuery(value);
		// selectedIndex reset is handled by updateSearchQueryAtom
	};

	// Handle keyboard navigation
	const handleKeyDown = (e: React.KeyboardEvent) => {
		switch (e.key) {
			case 'ArrowDown':
				e.preventDefault();
				setSelectedIndex((prev) => Math.min(prev + 1, suggestions.length - 1));
				break;
			case 'ArrowUp':
				e.preventDefault();
				setSelectedIndex((prev) => Math.max(prev - 1, 0));
				break;
			case 'Enter':
				e.preventDefault();
				if (suggestions[selectedIndex]) {
					selectCommand(suggestions[selectedIndex]);
				}
				break;
			case 'Tab':
				e.preventDefault();
				if (suggestions[selectedIndex]) {
					setInputValue(suggestions[selectedIndex].name);
					updateSearchQuery(suggestions[selectedIndex].name);
				}
				break;
		}
	};

	return (
		<div className="flex flex-1 items-center">
			<input
				ref={inputRef}
				type="text"
				value={inputValue}
				onChange={handleChange}
				onKeyDown={handleKeyDown}
				placeholder="Type command name..."
				className="flex-1 bg-transparent outline-none"
				style={{ color: 'var(--cmd-input-text)' }}
				autoComplete="off"
				autoCorrect="off"
				autoCapitalize="off"
				spellCheck="false"
			/>
			{inputValue && (
				<span className="ml-2 text-xs" style={{ color: 'var(--hud-text-secondary)', opacity: 0.6 }}>
					{suggestions.length} matches
				</span>
			)}
		</div>
	);
}

export default CommandSearch;
