"use client";

import { useQuery } from "@tanstack/react-query";
import { Bot, Plus } from "lucide-react";
import Link from "next/link";
import { PageHeader } from "@/components/page-header";
import { Badge, Button, EmptyState, Mono, Panel, PageLoader } from "@/components/ui";
import { api } from "@/lib/api";
import { can, useAuth } from "@/lib/auth";
import { relativeTime } from "@/lib/utils";

export default function AgentsPage() {
  const { role } = useAuth();
  const agents = useQuery({ queryKey: ["agents"], queryFn: api.listAgents });

  return (
    <div>
      <PageHeader
        eyebrow="Build"
        title="Agents"
        description="Configured reasoners with a scoped tool allow-list, memory, and budgets."
        actions={
          can(role, "build") && (
            <Link href="/agents/new">
              <Button variant="primary">
                <Plus className="h-4 w-4" /> New agent
              </Button>
            </Link>
          )
        }
      />

      {agents.isLoading ? (
        <PageLoader />
      ) : (agents.data ?? []).length === 0 ? (
        <EmptyState
          icon={<Bot className="h-8 w-8" />}
          title="No agents yet"
          description="Create your first agent: give it a prompt, a model, and the tools it's allowed to use."
          action={
            can(role, "build") && (
              <Link href="/agents/new">
                <Button variant="primary">
                  <Plus className="h-4 w-4" /> New agent
                </Button>
              </Link>
            )
          }
        />
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {(agents.data ?? []).map((agent) => (
            <Link key={agent.id} href={`/agents/${agent.id}`}>
              <Panel className="h-full transition-colors hover:border-line-strong">
                <div className="flex items-start justify-between">
                  <div className="flex h-10 w-10 items-center justify-center rounded-xl border border-line bg-surface-2 text-accent">
                    <Bot className="h-5 w-5" />
                  </div>
                  <Mono className="text-faint">{agent.id.slice(0, 8)}</Mono>
                </div>
                <h3 className="mt-4 font-display text-lg font-semibold text-fg">{agent.name}</h3>
                <p className="mt-1 line-clamp-2 min-h-[2.5rem] text-sm text-muted">
                  {agent.description || "No description"}
                </p>
                <div className="mt-4 flex flex-wrap items-center gap-1.5">
                  <Badge>{agent.model || "no model"}</Badge>
                  <Badge tone="accent">{agent.tools.length} tools</Badge>
                </div>
                <div className="mt-4 text-xs text-faint">
                  Created {relativeTime(agent.created_at)}
                </div>
              </Panel>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
