Skip to content

Open-source status page, incident response and uptime monitoring

42.6 KB
Raw Blame
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import {
  dnsRecords,
  headerAssertion,
  jsonBodyAssertion,
  numberCompareDictionary,
  recordAssertion,
  recordCompareDictionary,
  statusAssertion,
  stringCompareDictionary,
  textBodyAssertion,
} from "@openstatus/assertions";
import {
  grpcTlsModes,
  monitorMethods,
} from "@openstatus/db/src/schema/monitors/constants";
import {
  Add,
  Api,
  Close,
  Globe,
  Network,
  Server,
  Speed,
} from "@openstatus/icons";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@openstatus/ui/components/ui/alert-dialog";
import { Button } from "@openstatus/ui/components/ui/button";
import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@openstatus/ui/components/ui/form";
import { Input } from "@openstatus/ui/components/ui/input";
import {
  RadioGroup,
  RadioGroupItem,
} from "@openstatus/ui/components/ui/radio-group";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@openstatus/ui/components/ui/select";
import { Textarea } from "@openstatus/ui/components/ui/textarea";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@openstatus/ui/components/ui/tooltip";
import { cn } from "@openstatus/ui/lib/utils";
import { headerPairSchema } from "@openstatus/utils";
import { isTRPCClientError } from "@trpc/client";
import { useEffect, useState, useTransition } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";

import { Link } from "@/components/common/link";
import {
  FormCard,
  FormCardContent,
  FormCardDescription,
  FormCardFooter,
  FormCardFooterInfo,
  FormCardHeader,
  FormCardSeparator,
  FormCardTitle,
} from "@/components/forms/form-card";

const TYPES = ["http", "tcp", "dns", "icmp", "grpc"] as const;
const GRPC_TLS_LABELS = {
  tls: "TLS (verify certificate)",
  tls_insecure: "TLS (skip verification)",
  plaintext: "Plaintext (h2c)",
} as const;
const HTTP_ASSERTION_TYPES = ["status", "header", "textBody"] as const;
const DNS_ASSERTION_TYPES = dnsRecords;

const schema = z.object({
  name: z.string().trim().min(1, "Name is required"),
  type: z.enum(TYPES),
  method: z.enum(monitorMethods),
  url: z.string().min(1, "URL is required"),
  headers: z.array(headerPairSchema),
  active: z.boolean().prefault(true),
  assertions: z.array(
    z.discriminatedUnion("type", [
      statusAssertion,
      headerAssertion,
      textBodyAssertion,
      jsonBodyAssertion,
      recordAssertion,
    ]),
  ),
  body: z.string().optional(),
  grpcService: z.string().optional(),
  grpcTls: z.enum(grpcTlsModes).prefault("tls"),
  skipCheck: z.boolean().prefault(false),
  saveCheck: z.boolean().prefault(false),
});

type FormValues = z.input<typeof schema>;

export function FormGeneral({
  defaultValues,
  disabled,
  onSubmit,
  ...props
}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
  defaultValues?: FormValues;
  onSubmit: (values: FormValues) => Promise<void>;
  disabled?: boolean;
}) {
  const [error, setError] = useState<string | null>(null);
  const form = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: defaultValues ?? {
      active: true,
      name: "",
      type: undefined,
      method: "GET",
      url: "",
      headers: [],
      body: "",
      assertions: [],
      grpcService: "",
      grpcTls: "tls",
      skipCheck: false,
      saveCheck: false,
    },
  });
  // Stable row ids so removing a row remounts the shifted controllers.
  const {
    fields: headerFields,
    append: appendHeader,
    remove: removeHeader,
  } = useFieldArray({ control: form.control, name: "headers" });
  const {
    fields: assertionFields,
    append: appendAssertion,
    remove: removeAssertion,
  } = useFieldArray({ control: form.control, name: "assertions" });
  const [isPending, startTransition] = useTransition();
  const watchType = form.watch("type");
  const watchMethod = form.watch("method");
  // Each type has its own reference page; only http and dns support assertions.
  const referenceUrl = `https://www.openstatus.dev/docs/reference/${watchType ?? "http"}-monitor/`;
  const hasAssertions = watchType === "http" || watchType === "dns";

  useEffect(() => {
    // NOTE: reset form when type changes
    if (watchType && !defaultValues) {
      form.setValue("assertions", []);
      form.setValue("body", "");
      form.setValue("headers", []);
      form.setValue("method", "GET");
      form.setValue("url", "");
    }
  }, [watchType, defaultValues, form]);

  function submitAction(values: FormValues) {
    console.log("submitAction", values);
    if (isPending || disabled) return;

    // Validate assertions based on type
    for (let i = 0; i < values.assertions.length; i++) {
      const assertion = values.assertions[i];

      if (assertion.type === "status") {
        if (typeof assertion.target !== "number" || assertion.target <= 0) {
          form.setError(`assertions.${i}.target`, {
            message: "Status target must be a positive number",
          });
          return;
        }
      } else if (assertion.type === "header") {
        if (!assertion.key || assertion.key.trim() === "") {
          form.setError(`assertions.${i}.key`, {
            message: "Header key is required",
          });
          return;
        }
        if (!assertion.target || assertion.target.trim() === "") {
          form.setError(`assertions.${i}.target`, {
            message: "Header target is required",
          });
          return;
        }
      } else if (assertion.type === "textBody") {
        if (!assertion.target || assertion.target.trim() === "") {
          form.setError(`assertions.${i}.target`, {
            message: "Body target is required",
          });
          return;
        }
      } else if (assertion.type === "dnsRecord") {
        if (!assertion.key || assertion.key.trim() === "") {
          form.setError(`assertions.${i}.key`, {
            message: "DNS record key is required",
          });
          return;
        }
        if (!assertion.target || assertion.target.trim() === "") {
          form.setError(`assertions.${i}.target`, {
            message: "DNS record target is required",
          });
          return;
        }
      }
    }

    startTransition(async () => {
      try {
        const promise = onSubmit(values);
        toast.promise(promise, {
          loading: "Saving...",
          success: "Saved",
          error: (error) => {
            if (isTRPCClientError(error)) {
              setError(error.message);
              return error.message;
            }
            return "Failed to save";
          },
        });
        await promise;
      } catch (error) {
        console.error(error);
      }
    });
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(submitAction)} {...props}>
        <FormCard>
          <FormCardHeader>
            <FormCardTitle>Monitor Configuration</FormCardTitle>
            <FormCardDescription>
              Configure your monitor settings and endpoints.
            </FormCardDescription>
          </FormCardHeader>
          <FormCardContent className="grid gap-4 sm:grid-cols-3">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem className="sm:col-span-2">
                  <FormLabel>Name</FormLabel>
                  <FormControl>
                    <Input placeholder="OpenStatus API" {...field} />
                  </FormControl>
                  <FormMessage />
                  <FormDescription>
                    Internal name to identify the monitor in the dashboard.
                  </FormDescription>
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="active"
              render={({ field }) => (
                <FormItem className="sm:pt-5.5">
                  {/* pt = label height + gap, so the checkbox sits on the input line */}
                  <div className="flex items-center gap-2 sm:h-9">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    </FormControl>
                    <FormLabel>Active</FormLabel>
                  </div>
                  <FormDescription>Uncheck to pause checks.</FormDescription>
                </FormItem>
              )}
            />
          </FormCardContent>
          <FormCardSeparator />
          <FormCardContent>
            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Monitoring Type</FormLabel>
                  <FormControl>
                    <RadioGroup
                      onValueChange={field.onChange}
                      defaultValue={field.value}
                      className="grid grid-cols-2 gap-4 sm:grid-cols-5"
                      disabled={!!defaultValues?.type}
                    >
                      {[
                        { value: "http", icon: Globe, label: "HTTP" },
                        { value: "tcp", icon: Network, label: "TCP" },
                        { value: "dns", icon: Server, label: "DNS" },
                        { value: "icmp", icon: Speed, label: "ICMP" },
                        { value: "grpc", icon: Api, label: "gRPC" },
                      ].map((type) => {
                        return (
                          <Tooltip key={type.value}>
                            <TooltipTrigger asChild>
                              <FormItem
                                className={cn(
                                  "border-input has-aria-[invalid=true]:border-destructive has-data-[state=checked]:border-primary/50 has-focus-visible:border-ring has-focus-visible:ring-ring/50 relative flex cursor-pointer flex-row items-center gap-3 rounded-md border px-2 py-3 text-center shadow-xs transition-[color,box-shadow] outline-none has-focus-visible:ring-[3px]",
                                  defaultValues &&
                                    defaultValues.type !== type.value &&
                                    "pointer-events-none opacity-50",
                                )}
                              >
                                <FormControl>
                                  <RadioGroupItem
                                    value={type.value}
                                    className="sr-only"
                                    disabled={!!defaultValues?.type}
                                  />
                                </FormControl>
                                <type.icon
                                  className="text-muted-foreground shrink-0"
                                  size={16}
                                  aria-hidden="true"
                                />
                                <FormLabel className="text-foreground cursor-pointer text-xs leading-none font-medium after:absolute after:inset-0">
                                  {type.label}
                                </FormLabel>
                              </FormItem>
                            </TooltipTrigger>
                            <TooltipContent>
                              Monitor type cannot be changed after creation.
                            </TooltipContent>
                          </Tooltip>
                        );
                      })}
                      <div className="text-muted-foreground col-span-full text-xs">
                        Missing a type?{" "}
                        <a href="mailto:[email protected]">Contact us</a>
                      </div>
                    </RadioGroup>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </FormCardContent>
          {watchType ? <FormCardSeparator /> : null}
          {watchType === "http" && (
            <>
              <FormCardContent className="grid grid-cols-4 gap-4">
                <div className="col-span-1">
                  <FormField
                    control={form.control}
                    name="method"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Method</FormLabel>
                        <Select
                          onValueChange={field.onChange}
                          defaultValue={field.value}
                        >
                          <FormControl>
                            <SelectTrigger className="w-full">
                              <SelectValue placeholder="Select a method" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {monitorMethods.map((method) => (
                              <SelectItem key={method} value={method}>
                                {method}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <div className="col-span-3">
                  <FormField
                    control={form.control}
                    name="url"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>URL</FormLabel>
                        <FormControl>
                          <Input
                            placeholder="https://openstatus.dev"
                            type="url"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <FormItem className="col-span-full">
                  <FormLabel>Request Headers</FormLabel>
                  {headerFields.map((row, index) => (
                    <div key={row.id} className="grid gap-2 sm:grid-cols-5">
                      <FormField
                        control={form.control}
                        name={`headers.${index}.key`}
                        render={({ field }) => (
                          <FormItem className="col-span-2">
                            <FormControl>
                              <Input placeholder="Key" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name={`headers.${index}.value`}
                        render={({ field }) => (
                          <FormItem className="col-span-2">
                            <FormControl>
                              <Input placeholder="Value" {...field} />
                            </FormControl>
                          </FormItem>
                        )}
                      />
                      <Button
                        size="icon"
                        variant="ghost"
                        type="button"
                        aria-label="Remove header"
                        onClick={() => removeHeader(index)}
                      >
                        <Close />
                      </Button>
                    </div>
                  ))}
                  <div>
                    <Button
                      size="sm"
                      variant="outline"
                      type="button"
                      onClick={() => appendHeader({ key: "", value: "" })}
                    >
                      <Add />
                      Add Header
                    </Button>
                  </div>
                </FormItem>
                {["POST", "PUT", "PATCH", "DELETE"].includes(watchMethod) && (
                  <FormField
                    control={form.control}
                    name="body"
                    render={({ field }) => (
                      <FormItem className="col-span-full">
                        <FormLabel>Body</FormLabel>
                        <FormControl>
                          <Textarea {...field} />
                        </FormControl>
                        <FormDescription>Write your payload</FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </FormCardContent>
              <FormCardSeparator />
              <FormCardContent>
                <FormItem className="col-span-full">
                  <FormLabel>Assertions</FormLabel>
                  <FormDescription>
                    Validate the response to ensure your service is working as
                    expected. <br />
                    Add body, header, or status assertions.
                  </FormDescription>
                  {assertionFields.map((assertion, index) => (
                    <div
                      key={assertion.id}
                      className="grid gap-2 sm:grid-cols-6"
                    >
                      <FormField
                        control={form.control}
                        name={`assertions.${index}.type`}
                        render={({ field }) => (
                          <FormItem>
                            <Select
                              value={field.value}
                              onValueChange={field.onChange}
                              disabled={true}
                            >
                              <SelectTrigger
                                aria-invalid={
                                  !!form.formState.errors.assertions?.[index]
                                    ?.type
                                }
                                className="w-full"
                              >
                                <SelectValue placeholder="Select type" />
                              </SelectTrigger>
                              <SelectContent>
                                {HTTP_ASSERTION_TYPES.map((type) => (
                                  <SelectItem key={type} value={type}>
                                    {type}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name={`assertions.${index}.compare`}
                        render={({ field }) => (
                          <FormItem>
                            <Select
                              value={field.value}
                              onValueChange={field.onChange}
                            >
                              <SelectTrigger className="w-full min-w-16">
                                <span className="truncate">
                                  <SelectValue placeholder="Select compare" />
                                </span>
                              </SelectTrigger>
                              <SelectContent>
                                {assertion.type === "status"
                                  ? Object.entries(numberCompareDictionary).map(
                                      ([key, value]) => (
                                        <SelectItem key={key} value={key}>
                                          {value}
                                        </SelectItem>
                                      ),
                                    )
                                  : Object.entries(stringCompareDictionary).map(
                                      ([key, value]) => (
                                        <SelectItem key={key} value={key}>
                                          {value}
                                        </SelectItem>
                                      ),
                                    )}
                              </SelectContent>
                            </Select>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      {assertion.type === "header" && (
                        <FormField
                          control={form.control}
                          name={`assertions.${index}.key`}
                          render={({ field }) => (
                            <FormItem>
                              <Input
                                placeholder="Header key"
                                className="w-full"
                                {...field}
                                value={field.value as string}
                              />
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      )}
                      <FormField
                        control={form.control}
                        name={`assertions.${index}.target`}
                        render={({ field }) => (
                          <FormItem>
                            <Input
                              placeholder="Target value"
                              className="w-full"
                              type={
                                assertion.type === "status" ? "number" : "text"
                              }
                              {...field}
                              value={field.value?.toString() || ""}
                              onChange={(e) => {
                                const value =
                                  assertion.type === "status"
                                    ? Number.parseInt(e.target.value) || 0
                                    : e.target.value;
                                field.onChange(value);
                              }}
                            />
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <Button
                        size="icon"
                        variant="ghost"
                        type="button"
                        onClick={() => removeAssertion(index)}
                      >
                        <Close />
                      </Button>
                    </div>
                  ))}
                  <div className="flex flex-wrap gap-2">
                    <Button
                      size="sm"
                      variant="outline"
                      type="button"
                      onClick={() =>
                        appendAssertion({
                          type: "status",
                          version: "v1",
                          compare: "eq",
                          target: 200,
                        })
                      }
                    >
                      <Add />
                      Add Status Assertion
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      type="button"
                      onClick={() =>
                        appendAssertion({
                          type: "header",
                          version: "v1",
                          compare: "eq",
                          key: "",
                          target: "",
                        })
                      }
                    >
                      <Add />
                      Add Header Assertion
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      type="button"
                      onClick={() =>
                        appendAssertion({
                          type: "textBody",
                          version: "v1",
                          compare: "eq",
                          target: "",
                        })
                      }
                    >
                      <Add />
                      Add Body Assertion
                    </Button>
                  </div>
                </FormItem>
              </FormCardContent>
            </>
          )}
          {watchType === "tcp" && (
            <FormCardContent className="grid gap-4 sm:grid-cols-3">
              <FormField
                control={form.control}
                name="url"
                render={({ field }) => (
                  <FormItem className="sm:col-span-2">
                    <FormLabel>Host:Port</FormLabel>
                    <FormControl>
                      <Input placeholder="127.0.0.0.1:8080" {...field} />
                    </FormControl>
                    <FormMessage />
                    <FormDescription>
                      The input supports both IPv4 addresses and IPv6 addresses.
                    </FormDescription>
                  </FormItem>
                )}
              />
              <div className="text-muted-foreground col-span-full text-sm">
                Examples:
                <ul className="list-inside list-disc">
                  <li>
                    Domain:{" "}
                    <span className="text-foreground font-mono">
                      openstatus.dev:443
                    </span>
                  </li>
                  <li>
                    IPv4:{" "}
                    <span className="text-foreground font-mono">
                      192.168.1.1:443
                    </span>
                  </li>
                  <li>
                    IPv6:{" "}
                    <span className="text-foreground font-mono">
                      [2001:db8:85a3:8d3:1319:8a2e:370:7348]:443
                    </span>
                  </li>
                </ul>
              </div>
            </FormCardContent>
          )}
          {watchType === "icmp" && (
            <FormCardContent className="grid gap-4 sm:grid-cols-3">
              <FormField
                control={form.control}
                name="url"
                render={({ field }) => (
                  <FormItem className="sm:col-span-2">
                    <FormLabel>Host</FormLabel>
                    <FormControl>
                      <Input placeholder="1.1.1.1" {...field} />
                    </FormControl>
                    <FormMessage />
                    <FormDescription>
                      The host to ping. Supports a domain, IPv4, or IPv6 address
                      (no port).
                    </FormDescription>
                  </FormItem>
                )}
              />
              <div className="text-muted-foreground col-span-full text-sm">
                Examples:
                <ul className="list-inside list-disc">
                  <li>
                    Domain:{" "}
                    <span className="text-foreground font-mono">
                      openstatus.dev
                    </span>
                  </li>
                  <li>
                    IPv4:{" "}
                    <span className="text-foreground font-mono">1.1.1.1</span>
                  </li>
                  <li>
                    IPv6:{" "}
                    <span className="text-foreground font-mono">
                      2001:4860:4860::8888
                    </span>
                  </li>
                </ul>
              </div>
            </FormCardContent>
          )}
          {watchType === "grpc" && (
            <FormCardContent className="grid gap-4 sm:grid-cols-3">
              <FormField
                control={form.control}
                name="url"
                render={({ field }) => (
                  <FormItem className="sm:col-span-2">
                    <FormLabel>Host:Port</FormLabel>
                    <FormControl>
                      <Input placeholder="api.example.com:443" {...field} />
                    </FormControl>
                    <FormMessage />
                    <FormDescription>
                      The gRPC target. A port is required; bracket IPv6
                      addresses.
                    </FormDescription>
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="grpcTls"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>TLS</FormLabel>
                    <Select
                      onValueChange={field.onChange}
                      value={field.value ?? "tls"}
                    >
                      <FormControl>
                        <SelectTrigger className="w-full">
                          <SelectValue />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {grpcTlsModes.map((mode) => (
                          <SelectItem key={mode} value={mode}>
                            {GRPC_TLS_LABELS[mode]}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="grpcService"
                render={({ field }) => (
                  <FormItem className="col-span-full">
                    <FormLabel>Service</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="checkout.v1.CheckoutService"
                        {...field}
                        value={field.value ?? ""}
                      />
                    </FormControl>
                    <FormMessage />
                    <FormDescription>
                      The service name passed to grpc.health.v1.Health/Check.
                      Leave empty to check overall server health. This is a
                      service name, not a method path: entering
                      grpc.health.v1.Health itself returns SERVICE_UNKNOWN.
                    </FormDescription>
                  </FormItem>
                )}
              />
              <FormItem className="col-span-full">
                <FormLabel>Metadata</FormLabel>
                {headerFields.map((row, index) => (
                  <div key={row.id} className="grid gap-2 sm:grid-cols-5">
                    <FormField
                      control={form.control}
                      name={`headers.${index}.key`}
                      render={({ field }) => (
                        <FormItem className="col-span-2">
                          <FormControl>
                            <Input placeholder="Key" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                    <FormField
                      control={form.control}
                      name={`headers.${index}.value`}
                      render={({ field }) => (
                        <FormItem className="col-span-2">
                          <FormControl>
                            <Input placeholder="Value" {...field} />
                          </FormControl>
                        </FormItem>
                      )}
                    />
                    <Button
                      size="icon"
                      variant="ghost"
                      type="button"
                      aria-label="Remove header"
                      onClick={() => removeHeader(index)}
                    >
                      <Close />
                    </Button>
                  </div>
                ))}
                <div>
                  <Button
                    size="sm"
                    variant="outline"
                    type="button"
                    onClick={() => appendHeader({ key: "", value: "" })}
                  >
                    <Add />
                    Add Metadata
                  </Button>
                </div>
                <FormDescription>
                  Sent with the health check request, commonly for
                  authentication.
                </FormDescription>
              </FormItem>
            </FormCardContent>
          )}
          {watchType === "dns" && (
            <>
              <FormCardContent className="grid gap-4 sm:grid-cols-3">
                <FormField
                  control={form.control}
                  name="url"
                  render={({ field }) => (
                    <FormItem className="sm:col-span-2">
                      <FormLabel>URI</FormLabel>
                      <FormControl>
                        <Input placeholder="openstatus.dev" {...field} />
                      </FormControl>
                      <FormMessage />
                      <FormDescription>
                        The input supports both domain names and URIs.
                      </FormDescription>
                    </FormItem>
                  )}
                />
              </FormCardContent>
              <FormCardSeparator />
              <FormCardContent>
                <FormItem className="col-span-full">
                  <FormLabel>Assertions</FormLabel>
                  <FormDescription>
                    Validate the response to ensure your service is working as
                    expected. <br />
                    Add DNS record assertions.
                  </FormDescription>
                  {assertionFields.map((assertion, index) => (
                    <div
                      key={assertion.id}
                      className="grid gap-2 sm:grid-cols-6"
                    >
                      <FormField
                        control={form.control}
                        name={`assertions.${index}.type`}
                        defaultValue={"dnsRecord"}
                        render={({ field }) => (
                          <FormItem className="hidden">
                            <Select
                              value={field.value}
                              onValueChange={field.onChange}
                              disabled
                            >
                              <SelectTrigger className="w-full">
                                <SelectValue placeholder="Select type" />
                              </SelectTrigger>
                            </Select>
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name={`assertions.${index}.key`}
                        render={({ field }) => (
                          <FormItem>
                            <Select
                              value={field.value as string}
                              onValueChange={field.onChange}
                            >
                              <SelectTrigger
                                aria-invalid={
                                  !!form.formState.errors.assertions?.[index]
                                    ?.type
                                }
                                className="w-full"
                              >
                                <SelectValue placeholder="Select type" />
                              </SelectTrigger>
                              <SelectContent>
                                {DNS_ASSERTION_TYPES.map((type) => (
                                  <SelectItem key={type} value={type}>
                                    {type}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={form.control}
                        name={`assertions.${index}.compare`}
                        render={({ field }) => (
                          <FormItem>
                            <Select
                              value={field.value}
                              onValueChange={field.onChange}
                            >
                              <SelectTrigger className="w-full min-w-16">
                                <span className="truncate">
                                  <SelectValue placeholder="Select compare" />
                                </span>
                              </SelectTrigger>
                              <SelectContent>
                                {Object.entries(recordCompareDictionary).map(
                                  ([key, value]) => (
                                    <SelectItem key={key} value={key}>
                                      {value}
                                    </SelectItem>
                                  ),
                                )}
                              </SelectContent>
                            </Select>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      {assertion.type === "header" && (
                        <FormField
                          control={form.control}
                          name={`assertions.${index}.key`}
                          render={({ field }) => (
                            <FormItem>
                              <Input
                                placeholder="Header key"
                                className="w-full"
                                {...field}
                                value={field.value as string}
                              />
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      )}
                      <FormField
                        control={form.control}
                        name={`assertions.${index}.target`}
                        render={({ field }) => (
                          <FormItem>
                            <Input
                              placeholder="Target value"
                              className="w-full"
                              type={
                                assertion.type === "status" ? "number" : "text"
                              }
                              {...field}
                              value={field.value?.toString() || ""}
                              onChange={(e) => {
                                const value =
                                  assertion.type === "status"
                                    ? Number.parseInt(e.target.value) || 0
                                    : e.target.value;
                                field.onChange(value);
                              }}
                            />
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <Button
                        size="icon"
                        variant="ghost"
                        type="button"
                        onClick={() => removeAssertion(index)}
                      >
                        <Close />
                      </Button>
                    </div>
                  ))}
                  <div className="flex flex-wrap gap-2">
                    <Button
                      size="sm"
                      variant="outline"
                      type="button"
                      onClick={() =>
                        appendAssertion({
                          type: "dnsRecord",
                          version: "v1",
                          compare: "eq",
                          key: "A",
                          target: "",
                        })
                      }
                    >
                      <Add />
                      Add DNS Record Assertion
                    </Button>
                  </div>
                </FormItem>
              </FormCardContent>
            </>
          )}
          <FormCardFooter>
            <FormCardFooterInfo>
              Learn more about{" "}
              <Link href={referenceUrl} rel="noreferrer" target="_blank">
                Monitor Type
              </Link>
              {hasAssertions && (
                <>
                  {" "}
                  and{" "}
                  <Link
                    href={`${referenceUrl}#assertions`}
                    rel="noreferrer"
                    target="_blank"
                  >
                    Assertions
                  </Link>
                </>
              )}
              . We test your endpoint before saving the monitor.
            </FormCardFooterInfo>
            <Button type="submit" disabled={isPending || disabled}>
              {isPending ? "Submitting..." : "Submit"}
            </Button>
          </FormCardFooter>
        </FormCard>
        <AlertDialog open={!!error} onOpenChange={() => setError(null)}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>Still save?</AlertDialogTitle>
              <AlertDialogDescription>
                It seems like the endpoint is not reachable or the assertions
                failed. Do you want to save the monitor anyway?
              </AlertDialogDescription>
            </AlertDialogHeader>
            <div className="border-destructive/20 bg-destructive/10 max-h-48 overflow-auto rounded-md border p-2 whitespace-pre">
              <p className="text-destructive font-mono text-sm">{error}</p>
            </div>
            <AlertDialogFooter>
              <AlertDialogCancel type="button">Cancel</AlertDialogCancel>
              <AlertDialogAction
                type="button"
                onClick={async (e) => {
                  e.preventDefault();
                  form.setValue("skipCheck", true);
                  form.handleSubmit(submitAction)();
                  form.setValue("skipCheck", false);
                  setError(null);
                }}
                disabled={isPending}
              >
                Save
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </form>
    </Form>
  );
}