import React from "react";
import Head from "next/head";
import { get, post } from "@/common";

const ControlPage = () => {
  const [isBegin, setIsBegin] = React.useState(false);
  const [inputLimit, setInputLimit] = React.useState("2");
  const [token, setToken] = React.useState("");
  const toggleBegin = async () => {
    const json = await post("/api/config", { begin: !isBegin }, { token });
    setIsBegin(json.begin);
  };
  const refresh = async () => {
    const json = await get("/api/config");
    setInputLimit(json.limit);
    setIsBegin(json.begin);
  };
  React.useEffect(() => {
    refresh();
  }, []);
  return (
    <>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <p>
          <input
            value={token}
            onChange={(event) => setToken(event.target.value)}
            placeholder="Token"
          />
        </p>
        <p>
          <button onClick={() => toggleBegin()}>
            {isBegin ? "Pause" : "Begin"}
          </button>
        </p>
        <p>
          <input
            value={inputLimit}
            onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
              setInputLimit(event.target.value)
            }
          />
          <button
            onClick={() => {
              post(
                "/api/config",
                {
                  limit: parseInt(inputLimit) || 2,
                },
                { token }
              );
            }}
          >
            Set Limit
          </button>
        </p>
      </main>
    </>
  );
};

export default ControlPage;
