import { useEffect, useState } from "preact/hooks";
import { FabricGame, FabricInstaller, FabricLoader } from "../types/fabric.ts";
import { Loader } from "../components/Loader.tsx";
import { Button } from "../components/Button.tsx";

export function FabricVersions() {
  const [game, setGame] = useState<FabricGame[]>([]);
  const [installer, setInstaller] = useState<FabricInstaller[]>([]);
  const [loader, setLoader] = useState<FabricLoader[]>([]);
  const [isLoading, setIsLoading] = useState(true);

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

  useEffect(() => {
    let poll: number;
    if (isLoading) {
      poll = setInterval(async () => {
        const res = await fetch("/api/fabric");
        if (res.status !== 200) return;
        const json: {
          gameVersions: FabricGame[];
          installerVersions: FabricInstaller[];
          loaderVersions: FabricLoader[];
        } = await res.json();
        setGame(json.gameVersions);
        setInstaller(json.installerVersions);
        setLoader(json.loaderVersions);
        setIsLoading(false);
      }, 500);
    }

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

  return isLoading ? <Loader /> : (
    <form action="/api/fabric" 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.stable).map((g) => (
              <option>{g.version}</option>
            ))}
          </select>
          <br />
          <label>
            <input
              type="checkbox"
              checked={includeSnapshots}
              onChange={() => setIncludeSnapshots(!includeSnapshots)}
            />{" "}
            Include Snapshots?
          </label>
        </div>
        <div>
          <label class="block" htmlFor="loader">Loader Version</label>
          <select name="loader">
            {loader.map((g) => <option>{g.version}</option>)}
          </select>
          <small class="block">
            You probably don't need to change this one.
          </small>
        </div>
        <div>
          <label class="block" htmlFor="installer">Installer Version</label>
          <select name="installer">
            {installer.map((g) => <option>{g.version}</option>)}
          </select>
          <small class="block">
            You probably don't need to change this one.
          </small>
        </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>
  );
}
