import type { CombatantId } from "@initiative/domain";
import { type FormEvent, useCallback, useRef, useState } from "react";
import { useEncounter } from "./hooks/use-encounter";

function formatEvent(e: ReturnType<typeof useEncounter>["events"][number]) {
	switch (e.type) {
		case "TurnAdvanced":
			return `Turn: ${e.previousCombatantId} → ${e.newCombatantId} (round ${e.roundNumber})`;
		case "RoundAdvanced":
			return `Round advanced to ${e.newRoundNumber}`;
		case "CombatantAdded":
			return `Added combatant: ${e.name}`;
		case "CombatantRemoved":
			return `Removed combatant: ${e.name}`;
		case "CombatantUpdated":
			return `Renamed combatant: ${e.oldName} → ${e.newName}`;
	}
}

function EditableName({
	name,
	combatantId,
	isActive,
	onRename,
}: {
	name: string;
	combatantId: CombatantId;
	isActive: boolean;
	onRename: (id: CombatantId, newName: string) => void;
}) {
	const [editing, setEditing] = useState(false);
	const [draft, setDraft] = useState(name);
	const inputRef = useRef<HTMLInputElement>(null);

	const commit = useCallback(() => {
		const trimmed = draft.trim();
		if (trimmed !== "" && trimmed !== name) {
			onRename(combatantId, trimmed);
		}
		setEditing(false);
	}, [draft, name, combatantId, onRename]);

	const startEditing = useCallback(() => {
		setDraft(name);
		setEditing(true);
		requestAnimationFrame(() => inputRef.current?.select());
	}, [name]);

	if (editing) {
		return (
			<input
				ref={inputRef}
				type="text"
				value={draft}
				onChange={(e) => setDraft(e.target.value)}
				onBlur={commit}
				onKeyDown={(e) => {
					if (e.key === "Enter") commit();
					if (e.key === "Escape") setEditing(false);
				}}
			/>
		);
	}

	return (
		<button type="button" onClick={startEditing}>
			{isActive ? `▶ ${name}` : name}
		</button>
	);
}

export function App() {
	const {
		encounter,
		events,
		advanceTurn,
		addCombatant,
		removeCombatant,
		editCombatant,
	} = useEncounter();
	const activeCombatant = encounter.combatants[encounter.activeIndex];
	const [nameInput, setNameInput] = useState("");

	const handleAdd = (e: FormEvent) => {
		e.preventDefault();
		if (nameInput.trim() === "") return;
		addCombatant(nameInput);
		setNameInput("");
	};

	return (
		<div>
			<h1>Initiative Tracker</h1>

			{activeCombatant && (
				<p>
					Round {encounter.roundNumber} — Current: {activeCombatant.name}
				</p>
			)}

			<ul>
				{encounter.combatants.map((c, i) => (
					<li key={c.id}>
						<EditableName
							name={c.name}
							combatantId={c.id}
							isActive={i === encounter.activeIndex}
							onRename={editCombatant}
						/>{" "}
						<button type="button" onClick={() => removeCombatant(c.id)}>
							Remove
						</button>
					</li>
				))}
			</ul>

			<form onSubmit={handleAdd}>
				<input
					type="text"
					value={nameInput}
					onChange={(e) => setNameInput(e.target.value)}
					placeholder="Combatant name"
				/>
				<button type="submit">Add Combatant</button>
			</form>

			<button type="button" onClick={advanceTurn}>
				Next Turn
			</button>

			{events.length > 0 && (
				<div>
					<h2>Events</h2>
					<ul>
						{events.map((e, i) => (
							<li key={`${e.type}-${i}`}>{formatEvent(e)}</li>
						))}
					</ul>
				</div>
			)}
		</div>
	);
}
