"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { api } from "@/lib/api";
import type { DocumentTemplate } from "@/lib/types";
import { Breadcrumb } from "@/components/layout/Breadcrumb";
import { TemplateEditor } from "@/components/templates/TemplateEditor";
import { toast } from "sonner";

export default function NeueVorlagePage() {
  const router = useRouter();
  const queryClient = useQueryClient();

  const createMutation = useMutation({
    mutationFn: (data: Partial<DocumentTemplate>) =>
      api.post<DocumentTemplate>("/templates", data),
    onSuccess: (result) => {
      queryClient.invalidateQueries({ queryKey: ["templates"] });
      toast.success("Vorlage erstellt");
      router.push(`/vorlagen/${result.id}`);
    },
    onError: () => toast.error("Fehler beim Erstellen"),
  });

  return (
    <div className="animate-fade-in space-y-4">
      <Breadcrumb
        items={[
          { label: "Dashboard", href: "/dashboard" },
          { label: "Vorlagen", href: "/vorlagen" },
          { label: "Neue Vorlage" },
        ]}
      />

      <h1 className="text-lg font-semibold text-neutral-900">
        Neue Vorlage erstellen
      </h1>

      <TemplateEditor
        onSave={(data) => createMutation.mutate(data)}
        isSaving={createMutation.isPending}
      />
    </div>
  );
}
