"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 { 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-4 sm:p-6 lg:p-8">
            <Link href="/monitors" className="mb-2.5 inline-block text-sm text-text-secondary hover:text-text-primary">
                ← Monitors
            </Link>
            <div className="mb-5">
                <p className="font-mono text-[10px] uppercase tracking-[0.16em] text-text-tertiary">New check</p>
                <h1 className="mt-1 text-2xl font-bold tracking-tight text-text-primary">Watch something</h1>
            </div>

            <MonitorForm submitLabel="Create monitor" onSubmit={create} isPending={isPending} error={error as Error | null} />
        </div>
    );
}
