"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { api, MonitorInput } from "@/lib/api";
import { Card } from "@/components/ui";
import { MonitorForm } from "@/components/monitors/MonitorForm";

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

  const { mutate: create, isPending, error } = useMutation({
    mutationFn: (input: MonitorInput) => api.createMonitor(input),
    onSuccess: (m) => {
      queryClient.invalidateQueries({ queryKey: ["monitors"] });
      router.push(`/monitors/${m.monitor_id}`);
    },
  });

  return (
    <div className="p-8">
      <Link href="/monitors" className="text-sm text-text-secondary hover:text-text-primary">
        ← Monitors
      </Link>
      <h1 className="mb-6 mt-2 text-2xl font-bold text-text-primary">New Monitor</h1>

      <Card className="max-w-2xl">
        <MonitorForm submitLabel="Create Monitor" onSubmit={create} isPending={isPending} error={error as Error | null} />
      </Card>
    </div>
  );
}
