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, textLinkClass } from "../components/ui";
import { StateBadge } from "../components/StateBadge";
import { AgentAvatar } from "../components/AgentAvatar";
import { ChevronRightIcon } from "../components/icons";
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-7 grid grid-cols-2 gap-2.5 sm:mb-8 sm:grid-cols-4 sm:gap-3">
				{summaryTiles.map((t) => (
					<Card key={t.state} className="p-3.5 sm:p-4">
						<p className="text-2xl font-bold text-text tabular-nums sm:text-3xl">
							{counts[t.state] ?? 0}
						</p>
						<p className="mt-0.5 text-xs text-muted sm:mt-1">{t.label}</p>
					</Card>
				))}
			</div>

			{/* min-w-0 on both tracks: grid items default to min-width:auto, so the
			    truncated meta lines below would otherwise widen the column past the
			    viewport on narrow phones. */}
			<div className="grid gap-7 lg:grid-cols-3 lg:gap-8">
				<div className="min-w-0 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={textLinkClass}>
							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-2.5">
							{pending.map((r) => (
								<PendingRow key={r.request_id} request={r} />
							))}
						</div>
					)}
				</div>

				<div className="min-w-0">
					<div className="mb-3 flex items-center justify-between gap-3">
						<h2 className="text-lg font-semibold">Agents</h2>
						<Link to="/agents" className={textLinkClass}>
							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="tap flex items-start gap-3 p-3.5 hover:border-border-strong hover:bg-surface-raised/40 active:bg-surface-raised/60 sm:p-4">
				<AgentAvatar name={request.agent?.name ?? "?"} iconUrl={request.agent?.icon_url} size={32} />

				<div className="min-w-0 flex-1">
					<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
						<p className="min-w-0 break-words font-medium leading-snug 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-1 truncate text-xs text-muted">
						{request.agent?.name} · {request.changes.length} change
						{request.changes.length === 1 ? "" : "s"} · {relativeTime(request.created_at)}
					</p>
					{/* Stacked under the title on phones, where a side column would
					    squeeze the text to a couple of words per line. */}
					<div className="mt-2 flex flex-wrap items-center gap-2 sm:hidden">
						<StateBadge state={request.state} />
						<span className={`text-[11px] ${exp.urgent ? "text-pending" : "text-faint"}`}>
							{exp.text}
						</span>
					</div>
				</div>

				<div className="hidden shrink-0 flex-col items-end gap-1 sm:flex">
					<StateBadge state={request.state} />
					<span className={`text-[11px] ${exp.urgent ? "text-pending" : "text-faint"}`}>{exp.text}</span>
				</div>

				<ChevronRightIcon className="mt-1 h-5 w-5 shrink-0 text-faint sm:hidden" />
			</Card>
		</Link>
	);
}
