"use client";

import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ArrowLeft, Play, Trash2 } from "lucide-react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
import { AgentForm } from "@/components/agent-form";
import { PageHeader } from "@/components/page-header";
import { Button, Field, Mono, Panel, PageLoader, Textarea } from "@/components/ui";
import { api, ApiError } from "@/lib/api";
import { can, useAuth } from "@/lib/auth";

export default function AgentDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const qc = useQueryClient();
  const { role } = useAuth();
  const agent = useQuery({ queryKey: ["agent", id], queryFn: () => api.getAgent(id) });
  const [input, setInput] = useState("");
  const [running, setRunning] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (agent.isLoading) return <PageLoader />;
  if (!agent.data) return <div className="text-muted">Agent not found.</div>;

  return (
    <div>
      <Link href="/agents" className="mb-4 inline-flex items-center gap-1.5 text-sm text-muted hover:text-fg">
        <ArrowLeft className="h-4 w-4" /> Agents
      </Link>
      <PageHeader
        eyebrow={
          <span className="flex items-center gap-1.5">
            Agent · <Mono>{id.slice(0, 8)}</Mono>
          </span>
        }
        title={agent.data.name}
        description={agent.data.description}
        actions={
          can(role, "build") && (
            <Button
              variant="danger"
              onClick={async () => {
                if (!confirm("Delete this agent?")) return;
                await api.deleteAgent(id);
                await qc.invalidateQueries({ queryKey: ["agents"] });
                router.push("/agents");
              }}
            >
              <Trash2 className="h-4 w-4" /> Delete
            </Button>
          )
        }
      />

      {error && (
        <div className="mb-4 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">
          {error}
        </div>
      )}

      {can(role, "run") && (
        <Panel className="mb-6 border-accent/20">
          <span className="eyebrow">Run</span>
          <div className="mt-3 flex flex-col gap-3 sm:flex-row sm:items-end">
            <Field label="Input" className="flex-1">
              <Textarea
                rows={2}
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="Ask the agent to do something…"
              />
            </Field>
            <Button
              variant="primary"
              size="lg"
              loading={running}
              onClick={async () => {
                setRunning(true);
                setError(null);
                try {
                  const res = await api.runAgent(id, input);
                  router.push(`/runs/${res.run.id}`);
                } catch (err) {
                  setError(err instanceof ApiError ? err.message : "Run failed");
                  setRunning(false);
                }
              }}
            >
              <Play className="h-4 w-4" /> Run agent
            </Button>
          </div>
        </Panel>
      )}

      <Panel className="p-6 sm:p-8">
        <span className="eyebrow">Configuration</span>
        <div className="mt-5">
          <AgentForm
            initial={agent.data}
            submitLabel="Save changes"
            busy={saving}
            onSubmit={async (draft) => {
              setSaving(true);
              setError(null);
              try {
                await api.updateAgent(id, draft);
                await qc.invalidateQueries({ queryKey: ["agent", id] });
                await qc.invalidateQueries({ queryKey: ["agents"] });
              } catch (err) {
                setError(err instanceof ApiError ? err.message : "Save failed");
              } finally {
                setSaving(false);
              }
            }}
          />
        </div>
      </Panel>
    </div>
  );
}
