"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 { Card } from "@/components/ui";
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-8">
        <div className="rounded-lg border border-danger/30 bg-danger/10 p-4 text-danger">Monitor not found.</div>
      </div>
    );
  }

  return (
    <div className="p-8">
      <Link href={`/monitors/${monitorId}`} className="text-sm text-text-secondary hover:text-text-primary">
        ← {monitor.name}
      </Link>
      <h1 className="mb-6 mt-2 text-2xl font-bold text-text-primary">Edit Monitor</h1>

      <Card className="max-w-2xl">
        <MonitorForm initial={monitor} submitLabel="Save Changes" onSubmit={update} isPending={isPending} error={error as Error | null} />
      </Card>
    </div>
  );
}
