import {
	type CombatantId,
	type ConditionId,
	deriveHpStatus,
} from "@initiative/domain";
import { Brain, X } from "lucide-react";
import { type Ref, useCallback, useEffect, useRef, useState } from "react";
import { cn } from "../lib/utils";
import { AcShield } from "./ac-shield";
import { ConditionPicker } from "./condition-picker";
import { ConditionTags } from "./condition-tags";
import { D20Icon } from "./d20-icon";
import { HpAdjustPopover } from "./hp-adjust-popover";
import { Button } from "./ui/button";
import { Input } from "./ui/input";

interface Combatant {
	readonly id: CombatantId;
	readonly name: string;
	readonly initiative?: number;
	readonly maxHp?: number;
	readonly currentHp?: number;
	readonly ac?: number;
	readonly conditions?: readonly ConditionId[];
	readonly isConcentrating?: boolean;
}

interface CombatantRowProps {
	combatant: Combatant;
	isActive: boolean;
	onRename: (id: CombatantId, newName: string) => void;
	onSetInitiative: (id: CombatantId, value: number | undefined) => void;
	onRemove: (id: CombatantId) => void;
	onSetHp: (id: CombatantId, maxHp: number | undefined) => void;
	onAdjustHp: (id: CombatantId, delta: number) => void;
	onSetAc: (id: CombatantId, value: number | undefined) => void;
	onToggleCondition: (id: CombatantId, conditionId: ConditionId) => void;
	onToggleConcentration: (id: CombatantId) => void;
	onShowStatBlock?: () => void;
	onRollInitiative?: (id: CombatantId) => void;
}

function EditableName({
	name,
	combatantId,
	onRename,
}: {
	name: string;
	combatantId: CombatantId;
	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}
				className="h-7 text-sm"
				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={(e) => {
				e.stopPropagation();
				startEditing();
			}}
			className="truncate text-left text-sm text-foreground hover:text-primary transition-colors"
		>
			{name}
		</button>
	);
}

function MaxHpDisplay({
	maxHp,
	onCommit,
}: {
	maxHp: number | undefined;
	onCommit: (value: number | undefined) => void;
}) {
	const [editing, setEditing] = useState(false);
	const [draft, setDraft] = useState(maxHp?.toString() ?? "");
	const inputRef = useRef<HTMLInputElement>(null);

	const commit = useCallback(() => {
		if (draft === "") {
			onCommit(undefined);
		} else {
			const n = Number.parseInt(draft, 10);
			if (!Number.isNaN(n) && n >= 1) {
				onCommit(n);
			}
		}
		setEditing(false);
	}, [draft, onCommit]);

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

	if (editing) {
		return (
			<Input
				ref={inputRef}
				type="text"
				inputMode="numeric"
				value={draft}
				placeholder="Max"
				className="h-7 w-[7ch] text-center text-sm tabular-nums"
				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}
			className="inline-block h-7 min-w-[3ch] text-center text-sm leading-7 tabular-nums text-muted-foreground transition-colors hover:text-primary"
		>
			{maxHp ?? "Max"}
		</button>
	);
}

function ClickableHp({
	currentHp,
	maxHp,
	onAdjust,
	dimmed,
}: {
	currentHp: number | undefined;
	maxHp: number | undefined;
	onAdjust: (delta: number) => void;
	dimmed?: boolean;
}) {
	const [popoverOpen, setPopoverOpen] = useState(false);
	const status = deriveHpStatus(currentHp, maxHp);

	if (maxHp === undefined) {
		return (
			<span
				className={cn(
					"inline-block h-7 w-[4ch] text-center text-sm leading-7 tabular-nums text-muted-foreground",
					dimmed && "opacity-50",
				)}
			>
				--
			</span>
		);
	}

	return (
		<div className="relative">
			<button
				type="button"
				onClick={() => setPopoverOpen(true)}
				className={cn(
					"inline-block h-7 min-w-[3ch] text-center text-sm font-medium leading-7 tabular-nums transition-colors hover:text-primary",
					status === "bloodied" && "text-amber-400",
					status === "unconscious" && "text-red-400",
					status === "healthy" && "text-foreground",
					dimmed && "opacity-50",
				)}
			>
				{currentHp}
			</button>
			{popoverOpen && (
				<HpAdjustPopover
					onAdjust={onAdjust}
					onClose={() => setPopoverOpen(false)}
				/>
			)}
		</div>
	);
}

function AcDisplay({
	ac,
	onCommit,
}: {
	ac: number | undefined;
	onCommit: (value: number | undefined) => void;
}) {
	const [editing, setEditing] = useState(false);
	const [draft, setDraft] = useState(ac?.toString() ?? "");
	const inputRef = useRef<HTMLInputElement>(null);

	const commit = useCallback(() => {
		if (draft === "") {
			onCommit(undefined);
		} else {
			const n = Number.parseInt(draft, 10);
			if (!Number.isNaN(n) && n >= 0) {
				onCommit(n);
			}
		}
		setEditing(false);
	}, [draft, onCommit]);

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

	if (editing) {
		return (
			<Input
				ref={inputRef}
				type="text"
				inputMode="numeric"
				value={draft}
				placeholder="AC"
				className="h-7 w-[6ch] text-center text-sm tabular-nums"
				onChange={(e) => setDraft(e.target.value)}
				onBlur={commit}
				onKeyDown={(e) => {
					if (e.key === "Enter") commit();
					if (e.key === "Escape") setEditing(false);
				}}
			/>
		);
	}

	return <AcShield value={ac} onClick={startEditing} />;
}

function InitiativeDisplay({
	initiative,
	combatantId,
	dimmed,
	onSetInitiative,
	onRollInitiative,
}: {
	initiative: number | undefined;
	combatantId: CombatantId;
	dimmed: boolean;
	onSetInitiative: (id: CombatantId, value: number | undefined) => void;
	onRollInitiative?: (id: CombatantId) => void;
}) {
	const [editing, setEditing] = useState(false);
	const [draft, setDraft] = useState(initiative?.toString() ?? "");
	const inputRef = useRef<HTMLInputElement>(null);

	const commit = useCallback(() => {
		if (draft === "") {
			onSetInitiative(combatantId, undefined);
		} else {
			const n = Number.parseInt(draft, 10);
			if (!Number.isNaN(n)) {
				onSetInitiative(combatantId, n);
			}
		}
		setEditing(false);
	}, [draft, combatantId, onSetInitiative]);

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

	if (editing) {
		return (
			<Input
				ref={inputRef}
				type="text"
				inputMode="numeric"
				value={draft}
				placeholder="--"
				className={cn(
					"h-7 w-[6ch] text-center text-sm tabular-nums",
					dimmed && "opacity-50",
				)}
				onChange={(e) => setDraft(e.target.value)}
				onBlur={commit}
				onKeyDown={(e) => {
					if (e.key === "Enter") commit();
					if (e.key === "Escape") setEditing(false);
				}}
			/>
		);
	}

	// Empty + bestiary creature → d20 roll button
	if (initiative === undefined && onRollInitiative) {
		return (
			<button
				type="button"
				onClick={() => onRollInitiative(combatantId)}
				className={cn(
					"flex h-7 w-full items-center justify-center text-muted-foreground transition-colors hover:text-primary",
					dimmed && "opacity-50",
				)}
				title="Roll initiative"
				aria-label="Roll initiative"
			>
				<D20Icon className="h-7 w-7" />
			</button>
		);
	}

	// Has value → bold number, click to edit
	// Empty + manual → "--" placeholder, click to edit
	return (
		<button
			type="button"
			onClick={startEditing}
			className={cn(
				"h-7 w-full text-center text-sm leading-7 tabular-nums transition-colors",
				initiative !== undefined
					? "font-medium text-foreground hover:text-primary"
					: "text-muted-foreground hover:text-primary",
				dimmed && "opacity-50",
			)}
		>
			{initiative ?? "--"}
		</button>
	);
}

export function CombatantRow({
	ref,
	combatant,
	isActive,
	onRename,
	onSetInitiative,
	onRemove,
	onSetHp,
	onAdjustHp,
	onSetAc,
	onToggleCondition,
	onToggleConcentration,
	onShowStatBlock,
	onRollInitiative,
}: CombatantRowProps & { ref?: Ref<HTMLDivElement> }) {
	const { id, name, initiative, maxHp, currentHp } = combatant;
	const status = deriveHpStatus(currentHp, maxHp);
	const dimmed = status === "unconscious";
	const [pickerOpen, setPickerOpen] = useState(false);

	const prevHpRef = useRef(currentHp);
	const [isPulsing, setIsPulsing] = useState(false);
	const pulseTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);

	useEffect(() => {
		const prevHp = prevHpRef.current;
		prevHpRef.current = currentHp;

		if (
			prevHp !== undefined &&
			currentHp !== undefined &&
			currentHp < prevHp &&
			combatant.isConcentrating
		) {
			setIsPulsing(true);
			clearTimeout(pulseTimerRef.current);
			pulseTimerRef.current = setTimeout(() => setIsPulsing(false), 1200);
		}
	}, [currentHp, combatant.isConcentrating]);

	useEffect(() => {
		if (!combatant.isConcentrating) {
			clearTimeout(pulseTimerRef.current);
			setIsPulsing(false);
		}
	}, [combatant.isConcentrating]);

	return (
		/* biome-ignore lint/a11y/useKeyWithClickEvents: row click opens stat block */
		/* biome-ignore lint/a11y/noStaticElementInteractions: row click opens stat block */
		<div
			ref={ref}
			className={cn(
				"group rounded-md pr-3 transition-colors",
				isActive
					? "border-l-2 border-l-accent bg-accent/10"
					: combatant.isConcentrating
						? "border-l-2 border-l-purple-400"
						: "border-l-2 border-l-transparent",
				isPulsing && "animate-concentration-pulse",
				onShowStatBlock && "cursor-pointer",
			)}
			onClick={onShowStatBlock}
		>
			<div className="grid grid-cols-[2rem_3rem_1fr_auto_auto_2rem] items-center gap-3 py-2">
				{/* Concentration */}
				<button
					type="button"
					onClick={(e) => {
						e.stopPropagation();
						onToggleConcentration(id);
					}}
					title="Concentrating"
					aria-label="Toggle concentration"
					className={cn(
						"flex w-full items-center justify-center self-stretch -my-2 -ml-[2px] pl-[14px] transition-opacity",
						combatant.isConcentrating
							? dimmed
								? "opacity-50 text-purple-400"
								: "opacity-100 text-purple-400"
							: "opacity-0 group-hover:opacity-50 text-muted-foreground",
					)}
				>
					<Brain size={16} />
				</button>

				{/* Initiative */}
				{/* biome-ignore lint/a11y/useKeyWithClickEvents: stopPropagation wrapper */}
				{/* biome-ignore lint/a11y/noStaticElementInteractions: stopPropagation wrapper */}
				<div onClick={(e) => e.stopPropagation()}>
					<InitiativeDisplay
						initiative={initiative}
						combatantId={id}
						dimmed={dimmed}
						onSetInitiative={onSetInitiative}
						onRollInitiative={onRollInitiative}
					/>
				</div>

				{/* Name + Conditions */}
				<div
					className={cn(
						"relative flex flex-wrap items-center gap-1 min-w-0",
						dimmed && "opacity-50",
					)}
				>
					<span className="min-w-0 truncate">
						<EditableName name={name} combatantId={id} onRename={onRename} />
					</span>
					<ConditionTags
						conditions={combatant.conditions}
						onRemove={(conditionId) => onToggleCondition(id, conditionId)}
						onOpenPicker={() => setPickerOpen((prev) => !prev)}
					/>
					{pickerOpen && (
						<ConditionPicker
							activeConditions={combatant.conditions}
							onToggle={(conditionId) => onToggleCondition(id, conditionId)}
							onClose={() => setPickerOpen(false)}
						/>
					)}
				</div>

				{/* AC */}
				{/* biome-ignore lint/a11y/useKeyWithClickEvents: stopPropagation wrapper */}
				{/* biome-ignore lint/a11y/noStaticElementInteractions: stopPropagation wrapper */}
				<div
					className={cn(dimmed && "opacity-50")}
					onClick={(e) => e.stopPropagation()}
				>
					<AcDisplay ac={combatant.ac} onCommit={(v) => onSetAc(id, v)} />
				</div>

				{/* HP */}
				{/* biome-ignore lint/a11y/useKeyWithClickEvents: stopPropagation wrapper */}
				{/* biome-ignore lint/a11y/noStaticElementInteractions: stopPropagation wrapper */}
				<div
					className="flex items-center gap-1"
					onClick={(e) => e.stopPropagation()}
				>
					<ClickableHp
						currentHp={currentHp}
						maxHp={maxHp}
						onAdjust={(delta) => onAdjustHp(id, delta)}
						dimmed={dimmed}
					/>
					{maxHp !== undefined && (
						<span
							className={cn(
								"text-sm tabular-nums text-muted-foreground",
								dimmed && "opacity-50",
							)}
						>
							/
						</span>
					)}
					<div className={cn(dimmed && "opacity-50")}>
						<MaxHpDisplay maxHp={maxHp} onCommit={(v) => onSetHp(id, v)} />
					</div>
				</div>

				{/* Actions */}
				<Button
					variant="ghost"
					size="icon"
					className="h-7 w-7 text-muted-foreground hover:text-destructive opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto focus:opacity-100 focus:pointer-events-auto transition-opacity"
					onClick={(e) => {
						e.stopPropagation();
						onRemove(id);
					}}
					title="Remove combatant"
					aria-label="Remove combatant"
				>
					<X size={16} />
				</Button>
			</div>
		</div>
	);
}
