"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { api } from "@/lib/api";
import type { Case } from "@/lib/types";
import { CaseForm, type CaseFormData } from "@/components/cases/CaseForm";
import { ArrowLeft } from "lucide-react";
import Link from "next/link";

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

  const mutation = useMutation({
    mutationFn: (data: CaseFormData) => api.post<Case>("/cases", data),
    onSuccess: (created) => {
      queryClient.invalidateQueries({ queryKey: ["cases"] });
      toast.success("Akte angelegt");
      router.push(`/cases/${created.id}`);
    },
    onError: () => {
      toast.error("Fehler beim Anlegen der Akte");
    },
  });

  return (
    <div className="animate-fade-in mx-auto max-w-2xl">
      <Link
        href="/cases"
        className="mb-4 inline-flex items-center gap-1 text-sm text-neutral-500 transition-colors hover:text-neutral-700"
      >
        <ArrowLeft className="h-3.5 w-3.5" />
        Zurück zu Akten
      </Link>
      <h1 className="text-lg font-semibold text-neutral-900">Neue Akte</h1>
      <p className="mt-0.5 text-sm text-neutral-500">
        Neue Akte im System anlegen
      </p>
      <div className="mt-6 rounded-md border border-neutral-200 bg-white p-4 sm:p-6">
        <CaseForm
          onSubmit={(data) => mutation.mutate(data)}
          isSubmitting={mutation.isPending}
        />
      </div>
    </div>
  );
}
