"use client";

import { useQuery } from "@tanstack/react-query";
import { Activity, ArrowUpRight, Bot, Gavel, Workflow } from "lucide-react";
import Link from "next/link";
import { PageHeader } from "@/components/page-header";
import { StatusPill } from "@/components/status";
import { Badge, Mono, Panel } from "@/components/ui";
import { api } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { relativeTime } from "@/lib/utils";

function Stat({
  label,
  value,
  icon,
  href,
}: {
  label: string;
  value: React.ReactNode;
  icon: React.ReactNode;
  href: string;
}) {
  return (
    <Link href={href} className="group">
      <Panel className="transition-colors hover:border-line-strong">
        <div className="flex items-start justify-between">
          <span className="eyebrow">{label}</span>
          <span className="text-faint transition-colors group-hover:text-accent">{icon}</span>
        </div>
        <div className="mt-4 font-display text-4xl font-bold tracking-tight text-fg">{value}</div>
      </Panel>
    </Link>
  );
}

export default function DashboardPage() {
  const { currentWorkspace } = useAuth();
  const agents = useQuery({ queryKey: ["agents"], queryFn: api.listAgents });
  const runs = useQuery({ queryKey: ["runs"], queryFn: api.listRuns });
  const workflows = useQuery({ queryKey: ["workflows"], queryFn: api.listWorkflows });
  const approvals = useQuery({
    queryKey: ["approvals", "pending"],
    queryFn: () => api.listApprovals("pending"),
  });

  const recentRuns = (runs.data ?? []).slice(0, 6);

  return (
    <div>
      <PageHeader
        eyebrow={`Workspace · ${currentWorkspace?.slug ?? ""}`}
        title="Command deck"
        description="A live view of your agents, automations, and everything awaiting a decision."
      />

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Stat
          label="Agents"
          value={agents.data?.length ?? "-"}
          icon={<Bot className="h-5 w-5" />}
          href="/agents"
        />
        <Stat
          label="Workflows"
          value={workflows.data?.length ?? "-"}
          icon={<Workflow className="h-5 w-5" />}
          href="/workflows"
        />
        <Stat
          label="Total runs"
          value={runs.data?.length ?? "-"}
          icon={<Activity className="h-5 w-5" />}
          href="/runs"
        />
        <Stat
          label="Pending approvals"
          value={
            <span
              className={approvals.data && approvals.data.length > 0 ? "text-accent" : undefined}
            >
              {approvals.data?.length ?? "-"}
            </span>
          }
          icon={<Gavel className="h-5 w-5" />}
          href="/approvals"
        />
      </div>

      <div className="mt-8 grid gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2">
          <div className="mb-3 flex items-center justify-between">
            <span className="eyebrow">Recent runs</span>
            <Link href="/runs" className="text-xs text-muted hover:text-fg">
              View all
            </Link>
          </div>
          <Panel className="p-0">
            {recentRuns.length === 0 ? (
              <div className="px-5 py-10 text-center text-sm text-muted">No runs yet.</div>
            ) : (
              <div className="divide-y divide-line">
                {recentRuns.map((run) => (
                  <Link
                    key={run.id}
                    href={`/runs/${run.id}`}
                    className="flex items-center gap-4 px-5 py-3.5 transition-colors hover:bg-surface-2/40"
                  >
                    <StatusPill status={run.status} />
                    <Mono className="text-faint">{run.id.slice(0, 8)}</Mono>
                    <span className="text-sm text-muted">
                      {run.workflow_id ? "workflow" : "agent"} run
                    </span>
                    <div className="flex-1" />
                    <Badge>{run.total_steps} steps</Badge>
                    <span className="hidden text-xs text-faint sm:block">
                      {relativeTime(run.created_at)}
                    </span>
                    <ArrowUpRight className="h-4 w-4 text-faint" />
                  </Link>
                ))}
              </div>
            )}
          </Panel>
        </div>

        <div>
          <div className="mb-3 flex items-center justify-between">
            <span className="eyebrow">Needs you</span>
            <Link href="/approvals" className="text-xs text-muted hover:text-fg">
              Inbox
            </Link>
          </div>
          <Panel className="p-0">
            {(approvals.data ?? []).length === 0 ? (
              <div className="px-5 py-10 text-center text-sm text-muted">
                Nothing awaiting approval.
              </div>
            ) : (
              <div className="divide-y divide-line">
                {(approvals.data ?? []).slice(0, 5).map((a) => (
                  <Link
                    key={a.id}
                    href="/approvals"
                    className="block px-5 py-3.5 transition-colors hover:bg-surface-2/40"
                  >
                    <div className="flex items-center gap-2">
                      <Gavel className="h-4 w-4 text-warning" />
                      <span className="font-mono text-xs text-fg">{a.requested_tool}</span>
                    </div>
                    <p className="mt-1 line-clamp-1 text-xs text-muted">{a.summary}</p>
                  </Link>
                ))}
              </div>
            )}
          </Panel>
        </div>
      </div>
    </div>
  );
}
