import { useEffect, useState } from "preact/hooks";
import { Loader } from "../components/Loader.tsx";
import { Button } from "../components/Button.tsx";
import { ModrinthGameVersion } from "../lib/modrinth.ts";

export function ForgeVersions() {
  const [game, setGame] = useState<ModrinthGameVersion[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const [includeSnapshots, setIncludeSnapshots] = useState(false);

  useEffect(() => {
    let poll: number;
    if (isLoading) {
      poll = setInterval(async () => {
        const res = await fetch("/api/forge");
        if (res.status !== 200) return;
        const json: {
          gameVersions: ModrinthGameVersion[];
        } = await res.json();
        setGame(json.gameVersions);
        setIsLoading(false);
      }, 500);
    }

    return () => clearInterval(poll);
  }, [isLoading]);

  return isLoading ? <Loader /> : (
    <form action="/api/forge" method="POST">
      <div class="grid grid-cols-3 gap-8">
        <div>
          <label class="block" htmlFor="game">Game Version</label>
          <select name="game">
            {game.filter((g) => includeSnapshots || g.major).map((g) => (
              <option>{g.version}</option>
            ))}
          </select>
          <br />
          <label>
            <input
              type="checkbox"
              checked={includeSnapshots}
              onChange={() => setIncludeSnapshots(!includeSnapshots)}
            />{" "}
            Include Snapshots?
          </label>
        </div>
      </div>
      <div class="w-full">
        <Button
          class="ml-auto text-right text-lg font-pixel block mt-8"
          type="submit"
        >
          Let's Go!
        </Button>
      </div>
    </form>
  );
}
