"use client";

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

export default function EditMonitorPage() {
    const params = useParams();
    const router = useRouter();
    const queryClient = useQueryClient();
    const monitorId = params.id as string;

    const { data: monitor, isLoading } = useQuery({
        queryKey: ["monitors", monitorId],
        queryFn: () => api.getMonitor(monitorId),
    });

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

    if (isLoading) {
        return (
            <div className="flex h-full items-center justify-center">
                <div className="h-8 w-8 animate-spin rounded-full border-2 border-border border-t-accent" />
            </div>
        );
    }

    if (!monitor) {
        return (
            <div className="p-4 sm:p-6 lg:p-8">
                <div className="rounded-lg border border-danger/30 bg-danger/10 p-4 text-danger">
                    That monitor no longer exists.{" "}
                    <Link href="/monitors" className="underline">
                        Back to monitors
                    </Link>
                    .
                </div>
            </div>
        );
    }

    return (
        <div className="p-4 sm:p-6 lg:p-8">
            <Link href={`/monitors/${monitorId}`} className="mb-2.5 inline-block text-sm text-text-secondary hover:text-text-primary">
                ← {monitor.name}
            </Link>
            <div className="mb-5">
                <p className="font-mono text-[10px] uppercase tracking-[0.16em] text-text-tertiary">Editing</p>
                <h1 className="mt-1 text-2xl font-bold tracking-tight text-text-primary">{monitor.name}</h1>
            </div>

            <MonitorForm initial={monitor} submitLabel="Save changes" onSubmit={update} isPending={isPending} error={error as Error | null} />
        </div>
    );
}
