import { useEffect, useState } from "react";
import type { RetryState } from "../../types/events";
import type { RunPhaseState } from "../../types/runPhase";
import { formatRunPhaseLabel } from "../../utils/runPhase";
import styles from "./RunStatusBar.module.css";

interface RunStatusBarProps {
	isStreaming: boolean;
	isCompacting: boolean;
	runPhase: RunPhaseState | null;
	retryState: RetryState | null;
	onAbort: () => void;
	onAbortRetry: () => void;
}

function useElapsedSeconds(startedAt: number | undefined, active: boolean): number {
	const [elapsed, setElapsed] = useState(0);

	useEffect(() => {
		if (!active || startedAt == null) {
			setElapsed(0);
			return;
		}

		const tick = () => setElapsed(Math.max(0, Math.floor((Date.now() - startedAt) / 1000)));
		tick();
		const id = window.setInterval(tick, 1000);
		return () => window.clearInterval(id);
	}, [active, startedAt]);

	return elapsed;
}

export function RunStatusBar({
	isStreaming,
	isCompacting,
	runPhase,
	retryState,
	onAbort,
	onAbortRetry,
}: RunStatusBarProps) {
	const retryActive = Boolean(retryState?.active);
	const visible = isStreaming || isCompacting || retryActive;

	let label = "";
	let startedAt: number | undefined;

	if (retryActive) {
		const attempt = retryState?.attempt ?? 1;
		const max = retryState?.maxAttempts ?? attempt;
		label = `自动重试中 (${attempt}/${max})`;
		startedAt = retryState?.startedAt;
	} else if (isCompacting) {
		label = "整理上下文中…";
	} else if (runPhase) {
		label = formatRunPhaseLabel(runPhase.phase, runPhase.detail);
		startedAt = runPhase.startedAt;
	} else if (isStreaming) {
		label = "生成中…";
	}

	const elapsed = useElapsedSeconds(startedAt, visible);

	if (!visible) return null;

	return (
		<div className={styles.bar}>
			<div className={styles.statusText}>
				<span className={styles.dot} aria-hidden="true" />
				<span>{label}</span>
				{elapsed > 0 ? <span className={styles.elapsed}>{elapsed}s</span> : null}
				{retryActive && retryState?.errorMessage ? (
					<span className={styles.retryMeta}>{retryState.errorMessage.slice(0, 80)}</span>
				) : null}
			</div>
			<div className={styles.actions}>
				{retryActive ? (
					<button type="button" className={styles.cancelBtn} onClick={onAbortRetry}>
						取消重试
					</button>
				) : null}
				{isStreaming || isCompacting ? (
					<button type="button" className={styles.cancelBtn} onClick={onAbort}>
						中止
					</button>
				) : null}
			</div>
		</div>
	);
}
