"use client";

import {
	BarChart3Icon,
	CheckIcon,
	ChevronDownIcon,
	ClipboardListIcon,
	ClockIcon,
	DnaIcon,
	ExternalLinkIcon,
	FileTextIcon,
	FlaskConicalIcon,
	GitBranchIcon,
	GraduationCapIcon,
	HourglassIcon,
	Loader2Icon,
	MicroscopeIcon,
	type LucideIcon,
	RefreshCwIcon,
	ShieldCheckIcon,
	TrendingUpIcon,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { StepDetailSheet } from "@/components/training/step-detail-sheet";
import { cn } from "@/lib/utils";

type CardStatus = "pending" | "running" | "complete" | "failed" | "cancelled";
type PhaseTone = "complete" | "running" | "pending";

type PipelineCard = {
	key: string;
	icon?: string;
	title: string;
	subtitle: string;
	status: CardStatus;
	progress?: number;
};

type PipelinePhase = {
	key: string;
	label: string;
	tone: PhaseTone;
	cards: PipelineCard[];
};

type Kpi = {
	label: string;
	value: string;
	icon?: string;
};

type LogLine = {
	ts: string;
	iter: string | number;
	text: string;
};

type PipelinePayload = {
	session_id: string;
	generated_at_ms: number;
	status: { mode: string; state: CardStatus };
	kpis: Kpi[];
	phases: PipelinePhase[];
	logs: LogLine[];
};

const ICON_MAP: Record<string, LucideIcon> = {
	"bar-chart": BarChart3Icon,
	microscope: MicroscopeIcon,
	"trending-up": TrendingUpIcon,
	"file-text": FileTextIcon,
	dna: DnaIcon,
	"git-branch": GitBranchIcon,
	flask: FlaskConicalIcon,
	shield: ShieldCheckIcon,
	"graduation-cap": GraduationCapIcon,
	"clipboard-list": ClipboardListIcon,
	"refresh-cw": RefreshCwIcon,
	clock: ClockIcon,
	hourglass: HourglassIcon,
};

export function TrainingPipelinePanel({
	sessionId,
}: {
	sessionId: string | null;
}) {
	const [data, setData] = useState<PipelinePayload | null>(null);
	const [loading, setLoading] = useState(false);
	const [openCard, setOpenCard] = useState<{
		key: string;
		title: string;
		status: string;
	} | null>(null);

	useEffect(() => {
		setLoading(true);
		const url = sessionId
			? `/api/claw/training/pipeline/stream?session_id=${encodeURIComponent(sessionId)}`
			: "/api/claw/training/pipeline/stream";
		const es = new EventSource(url);
		es.onmessage = (ev) => {
			try {
				const payload = JSON.parse(ev.data);
				// program.md missing → backend pushes {available: false}; clear panel.
				if (payload && payload.available === false) {
					setData(null);
				} else {
					setData(payload);
				}
				setLoading(false);
			} catch {
				/* ignore malformed events */
			}
		};
		es.onerror = () => {
			// EventSource auto-reconnects; just stop showing the loading state.
			setLoading(false);
		};
		return () => {
			es.close();
		};
	}, [sessionId]);

	return (
		<div className="flex min-w-0 flex-1 flex-col overflow-hidden border-r bg-muted/20">
			<div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
				<HeaderRow status={data?.status ?? null} loading={loading} />
				<KpiRow kpis={data?.kpis ?? []} />
				<div className="mt-5 space-y-4">
					{!data ? (
						<div className="rounded-md border border-dashed p-8 text-center text-muted-foreground text-xs">
							暂无 pipeline 数据
						</div>
					) : (
						data.phases.map((phase) => (
							<PhaseSection
								key={phase.key}
								phase={phase}
								onCardClick={(card) =>
									setOpenCard({
										key: card.key,
										title: card.title,
										status: card.status,
									})
								}
							/>
						))
					)}
				</div>
			</div>
			<LogStream logs={data?.logs ?? []} />
			<StepDetailSheet
				sessionId={sessionId}
				stepKey={openCard?.key ?? null}
				stepTitle={openCard?.title}
				stepStatus={openCard?.status}
				open={openCard !== null}
				onOpenChange={(next) => {
					if (!next) setOpenCard(null);
				}}
			/>
		</div>
	);
}

function HeaderRow({
	status,
	loading,
}: {
	status: PipelinePayload["status"] | null;
	loading: boolean;
}) {
	const statusLabel = loading
		? "加载中"
		: status
			? `${status.mode} · ${statusText(status.state)}`
			: "暂无运行";
	const isRunning = status?.state === "running";
	return (
		<header className="flex items-center justify-between gap-3">
			<div className="flex items-center gap-2">
				<MicroscopeIcon className="size-5 text-muted-foreground" />
				<h2 className="font-semibold text-sm uppercase tracking-[0.2em] text-foreground/90">
					Training Pipeline Monitor
				</h2>
			</div>
			<div
				className={cn(
					"flex items-center gap-1.5 rounded-full border bg-emerald-500/10 px-3 py-1 text-emerald-700 text-xs dark:text-emerald-300",
					isRunning
						? "animate-pipeline-pill-glow border-emerald-400"
						: "border-emerald-500/40",
				)}
			>
				<span className="relative inline-flex size-2 items-center justify-center">
					<span
						className={cn(
							"size-2 rounded-full",
							isRunning
								? "bg-emerald-500"
								: status?.state === "complete"
									? "bg-emerald-500"
									: status?.state === "failed"
										? "bg-rose-500"
										: "bg-muted-foreground",
						)}
					/>
					{isRunning ? (
						<span className="pointer-events-none absolute inset-0 animate-pipeline-dot-ping rounded-full bg-emerald-400" />
					) : null}
				</span>
				<span className="font-medium">{statusLabel}</span>
			</div>
		</header>
	);
}

function KpiRow({ kpis }: { kpis: Kpi[] }) {
	if (!kpis.length) {
		return null;
	}
	return (
		<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-7">
			{kpis.map((kpi) => {
				const Icon = kpi.icon ? ICON_MAP[kpi.icon] : null;
				return (
					<div
						key={kpi.label}
						className="rounded-lg border bg-background px-3 py-2 min-h-[58px]"
					>
						<div className="text-[10px] font-medium tracking-wider text-muted-foreground truncate">
							{kpi.label}
						</div>
						<div className="mt-0.5 flex items-start gap-1.5 font-mono text-sm leading-tight text-foreground">
							<span className="break-all line-clamp-2">{kpi.value}</span>
							{Icon ? (
								<Icon className="size-3.5 shrink-0 text-muted-foreground mt-0.5" />
							) : null}
						</div>
					</div>
				);
			})}
		</div>
	);
}

function PhaseSection({
	phase,
	onCardClick,
}: {
	phase: PipelinePhase;
	onCardClick?: (card: PipelineCard) => void;
}) {
	const dotCls =
		phase.tone === "complete"
			? "bg-emerald-500"
			: phase.tone === "running"
				? "bg-sky-500"
				: "bg-violet-500";
	const arrowComplete = phase.tone === "complete";
	return (
		<section className="rounded-xl border bg-background/60 p-4">
			<div className="mb-3 flex items-center justify-between">
				<div className="flex items-center gap-2">
					<span className={cn("size-2 rounded-full", dotCls)} />
					<span className="font-medium text-foreground text-sm">
						{phase.label}
					</span>
				</div>
				<ChevronDownIcon className="size-4 text-muted-foreground/60" />
			</div>
			<div className="flex flex-wrap items-stretch gap-2">
				{phase.cards.map((card, idx) => (
					<div key={card.key} className="flex items-stretch gap-2">
						<PipelineCardView
							card={card}
							onClick={onCardClick ? () => onCardClick(card) : undefined}
						/>
						{idx < phase.cards.length - 1 ? (
							<PhaseArrow complete={arrowComplete} />
						) : null}
					</div>
				))}
			</div>
		</section>
	);
}

function PhaseArrow({ complete }: { complete: boolean }) {
	return (
		<div className="flex items-center px-1">
			<svg
				width="32"
				height="14"
				viewBox="0 0 32 14"
				fill="none"
				className={cn(
					complete ? "text-emerald-500" : "text-muted-foreground/40",
				)}
				aria-hidden
			>
				<line
					x1="0"
					y1="7"
					x2="22"
					y2="7"
					stroke="currentColor"
					strokeWidth="1.5"
					strokeDasharray={complete ? "3 3" : "0"}
				/>
				<path
					d="M22 2 L30 7 L22 12 Z"
					fill="currentColor"
					stroke="none"
				/>
			</svg>
		</div>
	);
}

function PipelineCardView({
	card,
	onClick,
}: {
	card: PipelineCard;
	onClick?: () => void;
}) {
	const isRunning = card.status === "running";
	const isComplete = card.status === "complete";
	const Icon = card.icon ? ICON_MAP[card.icon] : null;

	const tone = isComplete
		? "border-emerald-500/40 bg-emerald-50/40 dark:bg-emerald-950/20"
		: isRunning
			? "border-sky-400 bg-sky-50/60 dark:bg-sky-950/30 ring-2 ring-sky-300/50 dark:ring-sky-500/30 animate-pipeline-running-blue"
			: card.status === "failed"
				? "border-rose-500/40 bg-rose-50/40 dark:bg-rose-950/20"
				: "border-border bg-background";

	const Tag = onClick ? "button" : "div";

	return (
		<Tag
			type={onClick ? "button" : undefined}
			onClick={onClick}
			className={cn(
				"relative flex w-48 flex-col rounded-xl border px-3 pt-3 pb-2.5 text-left transition-colors",
				tone,
				onClick &&
					"cursor-pointer hover:brightness-105 hover:shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400",
			)}
		>
			<div className="mb-2 flex items-start">
				{isComplete ? (
					<div className="flex size-5 items-center justify-center rounded-full bg-emerald-500 text-white">
						<CheckIcon className="size-3" strokeWidth={3} />
					</div>
				) : (
					<StatusBadge status={card.status} />
				)}
			</div>
			<div className="flex items-center gap-1.5">
				{Icon ? (
					<Icon
						className={cn(
							"size-4 shrink-0",
							isComplete
								? "text-emerald-600 dark:text-emerald-400"
								: isRunning
									? "text-sky-600 dark:text-sky-400"
									: "text-muted-foreground",
						)}
					/>
				) : null}
				<span
					className={cn(
						"font-medium text-sm leading-tight",
						isRunning ? "text-foreground" : "",
						card.status === "pending" ? "text-muted-foreground" : "",
					)}
				>
					{card.title}
				</span>
			</div>
			<span className="mt-0.5 truncate font-mono text-[11px] text-muted-foreground">
				{card.subtitle}
			</span>
		</Tag>
	);
}

function StatusBadge({ status }: { status: CardStatus }) {
	const map: Record<CardStatus, { label: string; cls: string }> = {
		complete: {
			label: "DONE",
			cls: "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300",
		},
		running: {
			label: "RUNNING",
			cls: "bg-sky-500/20 text-sky-700 dark:text-sky-200",
		},
		pending: {
			label: "PENDING",
			cls: "bg-muted text-muted-foreground",
		},
		failed: {
			label: "FAILED",
			cls: "bg-rose-500/15 text-rose-700 dark:text-rose-300",
		},
		cancelled: {
			label: "CANCELLED",
			cls: "bg-muted text-muted-foreground",
		},
	};
	const { label, cls } = map[status];
	return (
		<span
			className={cn(
				"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[9px] font-semibold tracking-wider",
				cls,
			)}
		>
			{status === "running" ? (
				<Loader2Icon className="size-2.5 animate-spin" />
			) : null}
			{label}
		</span>
	);
}

function LogStream({ logs }: { logs: LogLine[] }) {
	const ref = useRef<HTMLDivElement>(null);
	useEffect(() => {
		if (ref.current) ref.current.scrollTop = ref.current.scrollHeight;
	}, [logs]);
	return (
		<div className="flex h-72 shrink-0 flex-col border-t bg-zinc-950 px-5 py-3">
			<div className="mb-2 flex shrink-0 items-center justify-between">
				<span className="font-semibold text-xs uppercase tracking-[0.18em] text-zinc-300">
					Live Log
				</span>
				<button
					type="button"
					className="inline-flex items-center gap-1 text-[11px] text-zinc-400 transition-colors hover:text-zinc-200"
				>
					查看全部
					<ExternalLinkIcon className="size-3" />
				</button>
			</div>
			<div
				ref={ref}
				className="min-h-0 flex-1 overflow-y-auto font-mono text-[12px] leading-6 text-zinc-100"
			>
				{logs.length === 0 ? (
					<div className="text-zinc-500">暂无日志</div>
				) : (
					logs.map((line, idx) => (
						<div key={idx} className="flex gap-3">
							<span className="text-zinc-500">{line.ts}</span>
							<span className="text-emerald-400">[iter={line.iter}]</span>
							<span>{line.text}</span>
						</div>
					))
				)}
			</div>
		</div>
	);
}

function statusText(state: CardStatus) {
	const map: Record<CardStatus, string> = {
		running: "Running",
		complete: "Complete",
		failed: "Failed",
		pending: "Idle",
		cancelled: "Cancelled",
	};
	return map[state];
}
