import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { requests as requestsApi, agents as agentsApi } from "../api/client";
import type { Agent, ChangeRequest, RequestState } from "../api/types";
import { useNotifications } from "../context/NotificationsContext";
import { Card, EmptyState, PageHeader, Spinner } from "../components/ui";
import { StateBadge } from "../components/StateBadge";
import { AgentAvatar } from "../components/AgentAvatar";
import { expiresIn, relativeTime } from "../utils";

const summaryTiles: { state: RequestState; label: string }[] = [
	{ state: "PENDING", label: "Pending" },
	{ state: "CHANGES_REQUESTED", label: "Changes requested" },
	{ state: "APPROVED", label: "Approved" },
	{ state: "CONSUMED", label: "Consumed" },
];

export function DashboardPage() {
	const { requestEventTick } = useNotifications();
	const [pending, setPending] = useState<ChangeRequest[]>([]);
	const [counts, setCounts] = useState<Record<string, number>>({});
	const [agents, setAgents] = useState<Agent[]>([]);
	const [loading, setLoading] = useState(true);

	const load = useCallback(async () => {
		try {
			const [list, summary, agentList] = await Promise.all([
				requestsApi.list({ state: "PENDING", page_size: 20 }),
				requestsApi.summary(),
				agentsApi.list(),
			]);
			setPending(list.requests);
			setCounts(summary.counts);
			setAgents(agentList);
		} finally {
			setLoading(false);
		}
	}, []);

	useEffect(() => {
		load();
	}, [load, requestEventTick]);

	if (loading) {
		return (
			<div className="flex justify-center py-20 text-primary">
				<Spinner className="h-7 w-7" />
			</div>
		);
	}

	return (
		<div>
			<PageHeader
				title="Dashboard"
				subtitle="Requests awaiting your review, and your connected agents."
			/>

			<div className="mb-8 grid grid-cols-2 gap-3 sm:grid-cols-4">
				{summaryTiles.map((t) => (
					<Card key={t.state} className="p-4">
						<p className="text-3xl font-bold text-text">{counts[t.state] ?? 0}</p>
						<p className="mt-1 text-xs text-muted">{t.label}</p>
					</Card>
				))}
			</div>

			<div className="grid gap-8 lg:grid-cols-3">
				<div className="lg:col-span-2">
					<div className="mb-3 flex items-center justify-between gap-3">
						<h2 className="text-lg font-semibold">Awaiting review</h2>
						<Link to="/requests" className="text-sm text-primary hover:underline">
							View all →
						</Link>
					</div>
					{pending.length === 0 ? (
						<EmptyState
							icon="🎉"
							title="You're all caught up"
							subtitle="No requests are waiting for your review right now."
						/>
					) : (
						<div className="space-y-3">
							{pending.map((r) => (
								<PendingRow key={r.request_id} request={r} />
							))}
						</div>
					)}
				</div>

				<div>
					<div className="mb-3 flex items-center justify-between gap-3">
						<h2 className="text-lg font-semibold">Agents</h2>
						<Link to="/agents" className="text-sm text-primary hover:underline">
							Manage →
						</Link>
					</div>
					{agents.length === 0 ? (
						<EmptyState icon="🤖" title="No agents yet" subtitle="Create an agent to start receiving requests." />
					) : (
						<div className="space-y-2">
							{agents.map((a) => (
								<Card key={a.id} className="flex items-center gap-3 p-3">
									<AgentAvatar name={a.name} iconUrl={a.icon_url} />
									<div className="min-w-0 flex-1">
										<p className="truncate text-sm font-medium">{a.name}</p>
										<p className="text-xs text-muted">
											{a.pending_count ?? 0}/{a.max_pending_requests} pending
											{a.disabled && <span className="ml-1 text-rejected">· disabled</span>}
										</p>
									</div>
								</Card>
							))}
						</div>
					)}
				</div>
			</div>
		</div>
	);
}

function PendingRow({ request }: { request: ChangeRequest }) {
	const exp = expiresIn(request.expires_at);
	return (
		<Link to={`/requests/${request.request_id}`} className="block">
			<Card className="p-4 transition hover:border-border-strong hover:bg-surface-raised/40">
				<div className="flex items-start justify-between gap-3">
					<div className="flex min-w-0 items-start gap-3">
						<AgentAvatar name={request.agent?.name ?? "?"} iconUrl={request.agent?.icon_url} size={32} />
						<div className="min-w-0">
							<div className="flex flex-wrap items-center gap-2">
								<p className="truncate font-medium text-text">{request.title}</p>
								{request.resubmitted && (
									<span className="animate-pulse-ring rounded-full bg-changes/20 px-2 py-0.5 text-[10px] font-semibold text-changes">
										UPDATED
									</span>
								)}
							</div>
							<p className="mt-0.5 truncate text-xs text-muted">
								{request.agent?.name} · {request.changes.length} change
								{request.changes.length === 1 ? "" : "s"} · {relativeTime(request.created_at)}
							</p>
						</div>
					</div>
					<div className="flex shrink-0 flex-col items-end gap-1">
						<StateBadge state={request.state} />
						<span className={`text-[11px] ${exp.urgent ? "text-pending" : "text-faint"}`}>{exp.text}</span>
					</div>
				</div>
			</Card>
		</Link>
	);
}
