import * as React from "react";
import { api } from "../api/client";
import { SLASH_COMMANDS, type SlashCommand } from "../slashCommands";

const {
	forwardRef,
	useCallback,
	useEffect,
	useImperativeHandle,
	useRef,
	useState,
} = React;

export interface ChatInputHandle {
	appendToInput(text: string): void;
}

interface ChatInputProps {
	loading: boolean;
	queuedMessages: { id: string; text: string }[];
	onSubmit: (message: string) => void;
	onCancel: () => void;
	onRemoveQueuedMessage: (id: string) => void;
}

/** Fuzzy-match: returns true if all chars of `query` appear in order in `str`. */
function fuzzyMatch(str: string, query: string): boolean {
	if (!query) return true;
	const lower = str.toLowerCase();
	const q = query.toLowerCase();
	let qi = 0;
	for (let i = 0; i < lower.length && qi < q.length; i++) {
		if (lower[i] === q[qi]) qi++;
	}
	return qi === q.length;
}

/** Score a fuzzy match: lower is better. Exact prefix match wins, then shorter paths. */
function fuzzyScore(str: string, query: string): number {
	const lower = str.toLowerCase();
	const q = query.toLowerCase();
	// Prefer matches where query appears as a contiguous substring
	if (lower.includes(q)) return lower.indexOf(q);
	return str.length;
}

interface FilePickerOverlayProps {
	query: string;
	files: string[];
	selectedIndex: number;
	onSelect: (file: string) => void;
	onDismiss: () => void;
	anchorRef: React.RefObject<HTMLTextAreaElement | null>;
}

function FilePickerOverlay({
	query,
	files,
	selectedIndex,
	onSelect,
}: FilePickerOverlayProps) {
	const filtered = files
		.filter((f) => fuzzyMatch(f, query))
		.sort((a, b) => fuzzyScore(a, query) - fuzzyScore(b, query))
		.slice(0, 10);

	if (filtered.length === 0) return null;

	return (
		<div
			data-testid="file-picker-overlay"
			style={{
				position: "absolute",
				bottom: "100%",
				left: 0,
				right: 0,
				background: "#1e1e1e",
				border: "1px solid #444",
				borderRadius: "8px",
				marginBottom: "6px",
				overflow: "hidden",
				zIndex: 100,
				boxShadow: "0 4px 16px rgba(0,0,0,0.4)",
				maxHeight: "240px",
				overflowY: "auto",
			}}
		>
			{filtered.map((file, idx) => (
				<button
					key={file}
					type="button"
					data-testid={`file-picker-item-${idx}`}
					onClick={() => onSelect(file)}
					style={{
						display: "block",
						width: "100%",
						textAlign: "left",
						padding: "8px 14px",
						background: idx === selectedIndex ? "#2d4a6e" : "transparent",
						border: "none",
						color: idx === selectedIndex ? "#ececec" : "#aaa",
						cursor: "pointer",
						fontFamily: "monospace",
						fontSize: "0.85rem",
						whiteSpace: "nowrap",
						overflow: "hidden",
						textOverflow: "ellipsis",
					}}
				>
					{file}
				</button>
			))}
		</div>
	);
}

interface SlashCommandPickerOverlayProps {
	query: string;
	selectedIndex: number;
	onSelect: (cmd: SlashCommand) => void;
}

function SlashCommandPickerOverlay({
	query,
	selectedIndex,
	onSelect,
}: SlashCommandPickerOverlayProps) {
	const filtered = SLASH_COMMANDS.filter((cmd) =>
		fuzzyMatch(cmd.name, query),
	).sort((a, b) => fuzzyScore(a.name, query) - fuzzyScore(b.name, query));

	if (filtered.length === 0) return null;

	return (
		<div
			data-testid="slash-command-picker"
			style={{
				position: "absolute",
				bottom: "100%",
				left: 0,
				right: 0,
				background: "#1e1e1e",
				border: "1px solid #444",
				borderRadius: "8px",
				marginBottom: "6px",
				overflow: "hidden",
				zIndex: 100,
				boxShadow: "0 4px 16px rgba(0,0,0,0.4)",
				maxHeight: "300px",
				overflowY: "auto",
			}}
		>
			{filtered.map((cmd, idx) => (
				<button
					key={cmd.name}
					type="button"
					data-testid={`slash-command-item-${idx}`}
					onClick={() => onSelect(cmd)}
					style={{
						display: "flex",
						flexDirection: "column",
						width: "100%",
						textAlign: "left",
						padding: "10px 14px",
						background: idx === selectedIndex ? "#2d4a6e" : "transparent",
						border: "none",
						cursor: "pointer",
						gap: "2px",
					}}
				>
					<code
						style={{
							fontSize: "0.88rem",
							color: idx === selectedIndex ? "#ececec" : "#e0e0e0",
							fontFamily: "monospace",
						}}
					>
						{cmd.name}
					</code>
					<span
						style={{
							fontSize: "0.78rem",
							color: idx === selectedIndex ? "#b0c0d0" : "#888",
						}}
					>
						{cmd.description}
					</span>
				</button>
			))}
		</div>
	);
}

export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(
	function ChatInput(
		{ loading, queuedMessages, onSubmit, onCancel, onRemoveQueuedMessage },
		ref,
	) {
		const [input, setInput] = useState("");
		const inputRef = useRef<HTMLTextAreaElement>(null);

		// File picker state
		const [projectFiles, setProjectFiles] = useState<string[]>([]);
		const [pickerQuery, setPickerQuery] = useState<string | null>(null);
		const [pickerSelectedIndex, setPickerSelectedIndex] = useState(0);
		const [pickerAtStart, setPickerAtStart] = useState(0);

		// Slash command picker state
		const [slashQuery, setSlashQuery] = useState<string | null>(null);
		const [slashSelectedIndex, setSlashSelectedIndex] = useState(0);

		useImperativeHandle(ref, () => ({
			appendToInput(text: string) {
				setInput((prev) => (prev ? `${prev}\n${text}` : text));
			},
		}));

		useEffect(() => {
			inputRef.current?.focus();
		}, []);

		// Compute filtered files for current picker query
		const filteredFiles =
			pickerQuery !== null
				? projectFiles
						.filter((f) => fuzzyMatch(f, pickerQuery))
						.sort(
							(a, b) => fuzzyScore(a, pickerQuery) - fuzzyScore(b, pickerQuery),
						)
						.slice(0, 10)
				: [];

		const dismissPicker = useCallback(() => {
			setPickerQuery(null);
			setPickerSelectedIndex(0);
		}, []);

		// Compute filtered slash commands for current query
		const filteredCommands =
			slashQuery !== null
				? SLASH_COMMANDS.filter((cmd) => fuzzyMatch(cmd.name, slashQuery)).sort(
						(a, b) =>
							fuzzyScore(a.name, slashQuery) - fuzzyScore(b.name, slashQuery),
					)
				: [];

		const dismissSlashPicker = useCallback(() => {
			setSlashQuery(null);
			setSlashSelectedIndex(0);
		}, []);

		const selectCommand = useCallback(
			(cmd: SlashCommand) => {
				// Extract base command (first word, e.g. "/assign" from "/assign <number> <model>")
				const baseCommand = cmd.name.split(" ")[0];
				setInput(`${baseCommand} `);
				dismissSlashPicker();
				setTimeout(() => inputRef.current?.focus(), 0);
			},
			[dismissSlashPicker],
		);

		const selectFile = useCallback(
			(file: string) => {
				// Replace the @query portion with @file
				const before = input.slice(0, pickerAtStart);
				const cursorPos = inputRef.current?.selectionStart ?? input.length;
				const after = input.slice(cursorPos);
				setInput(`${before}@${file}${after}`);
				dismissPicker();
				// Restore focus after state update
				setTimeout(() => inputRef.current?.focus(), 0);
			},
			[input, pickerAtStart, dismissPicker],
		);

		const handleInputChange = useCallback(
			(e: React.ChangeEvent<HTMLTextAreaElement>) => {
				const val = e.target.value;
				setInput(val);

				const cursor = e.target.selectionStart ?? val.length;
				const textUpToCursor = val.slice(0, cursor);

				// Slash command picker: triggered when input starts with / and no space yet
				const slashMatch = textUpToCursor.match(/^\/(\S*)$/);
				if (slashMatch) {
					setSlashQuery(slashMatch[1]);
					setSlashSelectedIndex(0);
					if (pickerQuery !== null) dismissPicker();
					return;
				}
				if (slashQuery !== null) dismissSlashPicker();

				// File picker: triggered by @ at start or after whitespace
				const atMatch = textUpToCursor.match(/(^|[\s\n])@([^\s@]*)$/);
				if (atMatch) {
					const query = atMatch[2];
					const atPos = textUpToCursor.lastIndexOf("@");
					setPickerAtStart(atPos);
					setPickerQuery(query);
					setPickerSelectedIndex(0);

					// Lazily load files on first trigger
					if (projectFiles.length === 0) {
						api
							.listProjectFiles()
							.then(setProjectFiles)
							.catch(() => {});
					}
				} else {
					if (pickerQuery !== null) dismissPicker();
				}
			},
			[
				projectFiles.length,
				pickerQuery,
				dismissPicker,
				slashQuery,
				dismissSlashPicker,
			],
		);

		const handleKeyDown = useCallback(
			(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
				// Slash command picker navigation
				if (slashQuery !== null && filteredCommands.length > 0) {
					if (e.key === "ArrowDown") {
						e.preventDefault();
						setSlashSelectedIndex((i) =>
							Math.min(i + 1, filteredCommands.length - 1),
						);
						return;
					}
					if (e.key === "ArrowUp") {
						e.preventDefault();
						setSlashSelectedIndex((i) => Math.max(i - 1, 0));
						return;
					}
					if (e.key === "Tab" || e.key === "Enter") {
						e.preventDefault();
						selectCommand(
							filteredCommands[slashSelectedIndex] ?? filteredCommands[0],
						);
						return;
					}
					if (e.key === "Escape") {
						e.preventDefault();
						dismissSlashPicker();
						return;
					}
				} else if (e.key === "Escape" && slashQuery !== null) {
					e.preventDefault();
					dismissSlashPicker();
					return;
				}

				// File picker navigation
				if (pickerQuery !== null && filteredFiles.length > 0) {
					if (e.key === "ArrowDown") {
						e.preventDefault();
						setPickerSelectedIndex((i) =>
							Math.min(i + 1, filteredFiles.length - 1),
						);
						return;
					}
					if (e.key === "ArrowUp") {
						e.preventDefault();
						setPickerSelectedIndex((i) => Math.max(i - 1, 0));
						return;
					}
					if (e.key === "Enter" || e.key === "Tab") {
						e.preventDefault();
						selectFile(filteredFiles[pickerSelectedIndex] ?? filteredFiles[0]);
						return;
					}
					if (e.key === "Escape") {
						e.preventDefault();
						dismissPicker();
						return;
					}
				} else if (e.key === "Escape" && pickerQuery !== null) {
					e.preventDefault();
					dismissPicker();
					return;
				}

				if (e.key === "Enter" && !e.shiftKey) {
					e.preventDefault();
					handleSubmit();
				}
			},
			[
				slashQuery,
				filteredCommands,
				slashSelectedIndex,
				selectCommand,
				dismissSlashPicker,
				pickerQuery,
				filteredFiles,
				pickerSelectedIndex,
				selectFile,
				dismissPicker,
			],
		);

		const handleSubmit = () => {
			if (!input.trim()) return;
			onSubmit(input);
			setInput("");
			dismissPicker();
			dismissSlashPicker();
		};

		return (
			<div
				style={{
					padding: "24px",
					background: "#171717",
					display: "flex",
					justifyContent: "center",
				}}
			>
				<div
					style={{
						maxWidth: "768px",
						width: "100%",
						display: "flex",
						flexDirection: "column",
						gap: "8px",
					}}
				>
					{/* Queued message indicators */}
					{queuedMessages.map(({ id, text }) => (
						<div
							key={id}
							data-testid="queued-message-indicator"
							style={{
								display: "flex",
								alignItems: "center",
								gap: "8px",
								padding: "8px 12px",
								background: "#1e1e1e",
								border: "1px solid #3a3a3a",
								borderRadius: "12px",
								fontSize: "0.875rem",
							}}
						>
							<span
								style={{
									color: "#666",
									flexShrink: 0,
									fontSize: "0.7rem",
									fontWeight: 700,
									letterSpacing: "0.05em",
									textTransform: "uppercase",
								}}
							>
								Queued
							</span>
							<span
								style={{
									color: "#888",
									flex: 1,
									overflow: "hidden",
									textOverflow: "ellipsis",
									whiteSpace: "nowrap",
								}}
							>
								{text}
							</span>
							<button
								type="button"
								title="Edit queued message"
								onClick={() => {
									setInput(text);
									onRemoveQueuedMessage(id);
									inputRef.current?.focus();
								}}
								style={{
									background: "none",
									border: "none",
									color: "#666",
									cursor: "pointer",
									padding: "2px 6px",
									fontSize: "0.8rem",
									flexShrink: 0,
									borderRadius: "4px",
								}}
							>
								Edit
							</button>
							<button
								type="button"
								title="Cancel queued message"
								onClick={() => onRemoveQueuedMessage(id)}
								style={{
									background: "none",
									border: "none",
									color: "#666",
									cursor: "pointer",
									padding: "2px 4px",
									fontSize: "0.875rem",
									flexShrink: 0,
									borderRadius: "4px",
								}}
							>
								✕
							</button>
						</div>
					))}
					{/* Input row with file picker overlay */}
					<div
						style={{
							display: "flex",
							gap: "8px",
							alignItems: "center",
							position: "relative",
						}}
					>
						{slashQuery !== null && (
							<SlashCommandPickerOverlay
								query={slashQuery}
								selectedIndex={slashSelectedIndex}
								onSelect={selectCommand}
							/>
						)}
						{pickerQuery !== null && (
							<FilePickerOverlay
								query={pickerQuery}
								files={projectFiles}
								selectedIndex={pickerSelectedIndex}
								onSelect={selectFile}
								onDismiss={dismissPicker}
								anchorRef={inputRef}
							/>
						)}
						<textarea
							ref={inputRef}
							value={input}
							onChange={handleInputChange}
							onKeyDown={handleKeyDown}
							placeholder="Send a message..."
							rows={1}
							style={{
								flex: 1,
								padding: "14px 20px",
								borderRadius: "24px",
								border: "1px solid #333",
								outline: "none",
								fontSize: "1rem",
								fontWeight: "500",
								background: "#2f2f2f",
								color: "#ececec",
								boxShadow: "0 2px 6px rgba(0,0,0,0.02)",
								resize: "none",
								overflowY: "auto",
								fontFamily: "inherit",
							}}
						/>
						<button
							type="button"
							onClick={loading && !input.trim() ? onCancel : handleSubmit}
							disabled={!loading && !input.trim()}
							style={{
								background: "#ececec",
								color: "black",
								border: "none",
								borderRadius: "50%",
								width: "32px",
								height: "32px",
								display: "flex",
								alignItems: "center",
								justifyContent: "center",
								cursor: "pointer",
								opacity: !loading && !input.trim() ? 0.5 : 1,
								flexShrink: 0,
							}}
						>
							{loading && !input.trim() ? "■" : "↑"}
						</button>
					</div>
				</div>
			</div>
		);
	},
);
