"use client";

import { useQueryClient } from "@tanstack/react-query";
import { ArrowLeft } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { AgentForm } from "@/components/agent-form";
import { PageHeader } from "@/components/page-header";
import { Panel } from "@/components/ui";
import { api, ApiError } from "@/lib/api";

export default function NewAgentPage() {
  const router = useRouter();
  const qc = useQueryClient();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  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="Build · new" title="Design an agent" />
      {error && (
        <div className="mb-4 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">
          {error}
        </div>
      )}
      <Panel className="p-6 sm:p-8">
        <AgentForm
          submitLabel="Create agent"
          busy={busy}
          onSubmit={async (draft) => {
            setBusy(true);
            setError(null);
            try {
              const agent = await api.createAgent(draft);
              await qc.invalidateQueries({ queryKey: ["agents"] });
              router.push(`/agents/${agent.id}`);
            } catch (err) {
              setError(err instanceof ApiError ? err.message : "Failed to create agent");
              setBusy(false);
            }
          }}
        />
      </Panel>
    </div>
  );
}
