'use client';

import React, { useRef, useEffect, useState } from 'react';
import { useAtom, useSetAtom, useAtomValue } from 'jotai';
import {
	commandLineStateAtom,
	provideInputAtom,
	skipInputAtom,
	goBackInputAtom,
	inputModeAtom,
	currentInputAtom,
	commandProgressAtom,
} from '../../commands/store';
import { zoomAtom, panAtom, viewportRectAtom } from '../../core/viewport-store';
import { CollectorInputPhase } from './CollectorInputPhase';
import { CollectorSelectInput, CollectorBooleanInput } from './CollectorSelectInput';

// Re-export sub-components
export { CollectorInputPhase } from './CollectorInputPhase';
export type { CollectorInputPhaseProps } from './CollectorInputPhase';
export { CollectorSelectInput, CollectorBooleanInput } from './CollectorSelectInput';
export type { CollectorSelectInputProps, CollectorBooleanInputProps } from './CollectorSelectInput';

/**
 * CommandInputCollector
 *
 * Displays the current input prompt and collects user input.
 * Handles different input types: text, number, select, point, node, etc.
 *
 * @refactored 1.4.0 — Extracted CollectorInputPhase, CollectorSelectInput, CollectorBooleanInput
 */
export function CommandInputCollector() {
	const [state] = useAtom(commandLineStateAtom);
	const currentInput = useAtomValue(currentInputAtom);
	const progress = useAtomValue(commandProgressAtom);
	const inputMode = useAtomValue(inputModeAtom);
	const provideInput = useSetAtom(provideInputAtom);
	const skipInput = useSetAtom(skipInputAtom);
	const goBack = useSetAtom(goBackInputAtom);

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

	const zoom = useAtomValue(zoomAtom);
	const pan = useAtomValue(panAtom);
	const viewportRect = useAtomValue(viewportRectAtom);

	// Focus input when in text/number/point mode
	useEffect(() => {
		if (currentInput && (currentInput.type === 'text' || currentInput.type === 'number' || currentInput.type === 'point')) {
			inputRef.current?.focus();
		}
	}, [currentInput]);

	// Reset text value when input changes
	useEffect(() => {
		setTextValue('');
	}, [currentInput?.name]);

	const getWorldCenter = () => {
		const screenCenterX = viewportRect ? viewportRect.width / 2 : window.innerWidth / 2;
		const screenCenterY = viewportRect ? viewportRect.height / 2 : window.innerHeight / 2;
		return { x: Math.round((screenCenterX - pan.x) / zoom), y: Math.round((screenCenterY - pan.y) / zoom) };
	};

	// Global keyboard handler for select shortcuts and Enter for defaults
	useEffect(() => {
		if (!currentInput) return;
		const handleGlobalKeyDown = (e: KeyboardEvent) => {
			const target = e.target as HTMLElement;
			const isInputField = target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;

			if (e.key === 'Enter' && !isInputField) {
				if (currentInput.type === 'point') { e.preventDefault(); provideInput(getWorldCenter()); return; }
				if (currentInput.default !== undefined) { e.preventDefault(); provideInput(currentInput.default); return; }
			}
			if (currentInput.type === 'select' && currentInput.options) {
				const option = currentInput.options.find((opt) => opt.shortcut.toLowerCase() === e.key.toLowerCase());
				if (option) { e.preventDefault(); provideInput(option.value); }
			}
			if (currentInput.type === 'boolean') {
				if (e.key.toLowerCase() === 'y') { e.preventDefault(); provideInput(true); }
				if (e.key.toLowerCase() === 'n') { e.preventDefault(); provideInput(false); }
			}
		};
		window.addEventListener('keydown', handleGlobalKeyDown);
		return () => window.removeEventListener('keydown', handleGlobalKeyDown);
	}, [currentInput, provideInput, getWorldCenter]);

	const handleSubmit = (e: React.FormEvent) => {
		e.preventDefault();
		if (!currentInput) return;
		if (textValue === '' && currentInput.default !== undefined) { provideInput(currentInput.default); setTextValue(''); return; }
		if (currentInput.type === 'number') { const num = parseFloat(textValue); if (!isNaN(num)) provideInput(num); }
		else provideInput(textValue);
		setTextValue('');
	};

	const handleKeyDown = (e: React.KeyboardEvent) => {
		if (e.key === 'Escape') {
			e.preventDefault();
			if (currentInput?.required === false) skipInput();
			else if (progress && progress.current > 1) goBack();
			return;
		}
		if (e.key === 'Backspace' && textValue === '' && progress && progress.current > 1) { e.preventDefault(); goBack(); return; }
		if (currentInput?.type === 'select' && currentInput.options) {
			const option = currentInput.options.find((opt) => opt.shortcut.toLowerCase() === e.key.toLowerCase());
			if (option) { e.preventDefault(); provideInput(option.value); }
		}
	};

	if (state.phase !== 'collecting' || !currentInput) return null;

	const isSelectMode = currentInput.type === 'select';

	return (
		<div className="flex flex-1 flex-col gap-1">
			<CollectorInputPhase
				command={state.command}
				currentInput={currentInput}
				progress={progress}
				inputModeType={inputMode.type}
			/>

			<div className="flex items-center gap-2">
				<span style={{ color: 'var(--hud-text-secondary)' }}>{currentInput.prompt}:</span>

				{/* Select options */}
				{isSelectMode && currentInput.options && (
					<CollectorSelectInput options={currentInput.options} onSelect={(v) => provideInput(v)} />
				)}

				{/* Text/Number input */}
				{(currentInput.type === 'text' || currentInput.type === 'number') && (
					<form onSubmit={handleSubmit} className="flex flex-1 items-center">
						<input
							ref={inputRef}
							type={currentInput.type === 'number' ? 'number' : 'text'}
							value={textValue}
							onChange={(e) => setTextValue(e.target.value)}
							onKeyDown={handleKeyDown}
							placeholder={currentInput.default !== undefined ? `Default: ${currentInput.default}` : undefined}
							className="flex-1 bg-transparent outline-none"
							style={{ color: 'var(--cmd-input-text)' }}
							autoComplete="off" autoCorrect="off" autoCapitalize="off" spellCheck="false"
						/>
					</form>
				)}

				{/* Point input */}
				{currentInput.type === 'point' && (
					<form
						onSubmit={(e) => {
							e.preventDefault();
							if (textValue.trim() === '') { provideInput(getWorldCenter()); setTextValue(''); return; }
							const match = textValue.match(/^\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*$/);
							if (match) { provideInput({ x: parseFloat(match[1]), y: parseFloat(match[2]) }); setTextValue(''); }
						}}
						className="flex flex-1 items-center"
					>
						<input
							ref={inputRef} type="text" value={textValue}
							onChange={(e) => setTextValue(e.target.value)} onKeyDown={handleKeyDown}
							placeholder="x, y or click on canvas (Enter for center)"
							className="flex-1 bg-transparent outline-none"
							style={{ color: 'var(--cmd-input-text)' }} autoComplete="off"
						/>
					</form>
				)}

				{/* Boolean input */}
				{currentInput.type === 'boolean' && (
					<CollectorBooleanInput onSelect={(v) => provideInput(v)} />
				)}

				{/* Skip + Back buttons */}
				{currentInput.required === false && (
					<button
						onClick={() => skipInput()}
						className="rounded px-2 py-0.5 text-xs transition-colors"
						style={{ color: 'var(--hud-text-secondary)', opacity: 0.8 }}
						onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'var(--list-item-bg-hover)'; e.currentTarget.style.color = 'var(--hud-text)'; }}
						onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; e.currentTarget.style.color = 'var(--hud-text-secondary)'; }}
					>
						Skip (Esc)
					</button>
				)}

				{progress && progress.current > 1 && (
					<button
						onClick={() => goBack()}
						className="rounded px-2 py-0.5 text-xs transition-colors"
						style={{ color: 'var(--hud-text-secondary)', opacity: 0.8 }}
						onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = 'var(--list-item-bg-hover)'; e.currentTarget.style.color = 'var(--hud-text)'; }}
						onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; e.currentTarget.style.color = 'var(--hud-text-secondary)'; }}
					>
						Back
					</button>
				)}
			</div>
		</div>
	);
}

export default CommandInputCollector;
