import { FormEvent, useState } from "react";
import { Button, InputGroup, TextArea } from "@blueprintjs/core";
import { useNavigate } from "react-router";
import { useMutation, useQueryClient } from "react-query";

export default function Home() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();

  const [name, setName] = useState("");
  const [content, setContent] = useState("");

  const submitCreate = async (evt: FormEvent) => {
    evt.stopPropagation();
    evt.preventDefault();

    const formData = new FormData();
    formData.append("name", name);
    formData.append("config", content);

    const result = await fetch("/api/upload", {
      method: "POST",
      body: formData,
    });
    const { id } = await result.json();
    queryClient.invalidateQueries("service/list");
    navigate(`/service/${id}`);
  };

  return (
    <>
      <form onSubmit={submitCreate}>
        <InputGroup
          onChange={(evt) => setName(evt.target.value)}
          placeholder="Service name..."
        />
        <TextArea
          onChange={(evt) => setContent(evt.target.value)}
          placeholder="Service config (YML)..."
        />
        <Button type="submit">Submit</Button>
      </form>
    </>
  );
}
