import { useEffect, useState } from "preact/hooks";
import { useNavigate } from "react-router-dom";

export function Home() {
  const [loading, setLoading] = useState(true);
  const [mcPath, setMcPath] = useState("");
  const [worlds, setWorlds] = useState<{
    world: string;
    icon: string;
    path: string;
  }[]>([]);

  const fetchWorlds = async () => {
    const res = await fetch("/api/dir");
    const json = await res.json();
    setMcPath(json.mcPath);
    setWorlds(json.worlds);
    setLoading(false);
  };

  useEffect(() => {
    document.title = "BearMetal Packer";
    fetchWorlds();
  }, []);

  const submitMcPath = async (event: SubmitEvent) => {
    setLoading(true);
    event.preventDefault();
    const form = new FormData(event.target as HTMLFormElement);
    const res = await fetch("/api/dir", {
      method: "POST",
      body: form,
    });
    if (res.status === 200) {
      fetchWorlds();
    } else setLoading(false);
  };

  const nav = useNavigate();

  const setWorld = async (worldPath: string) => {
    setLoading(true);
    const res = await fetch("/api/world", {
      method: "POST",
      body: worldPath,
    });

    if (res.status === 200) {
      nav("/editor");
    } else setLoading(false);
  };

  return (
    <div class="grid h-full">
      <div class="place-self-center text-center max-h-96 bg-primary-400 rounded-lg p-4 overflow-scroll">
        <h1 class="text-3xl">Welcome BearMetal Packer</h1>
        <p>An all in one toolkit to build datapacks for Minecraft.</p>
        {loading ? <p>Hold tight, we're doing some heavy lifting.</p> : (
          <>
            {mcPath
              ? (
                <>
                  <p>Minecraft directory set to {mcPath}</p>
                  <p>Worlds:</p>
                  <ul class="w-full even:bg-black/5">
                    {worlds.map((world) => (
                      <li
                        class="flex gap-4 items-center cursor-pointer"
                        onClick={() => setWorld(world.path)}
                      >
                        <img
                          src={"/images?location=" + world.icon}
                          class="w-16 h-16"
                        />
                        {world.world}
                      </li>
                    ))}
                  </ul>
                </>
              )
              : (
                <>
                  <p>No Minecraft directory set, please set now:</p>
                  <form method="POST" onSubmit={submitMcPath}>
                    <input
                      type="text"
                      name="mcPath"
                      placeholder="Minecraft directory"
                    />
                    <button type="submit">Set</button>
                  </form>
                </>
              )}
          </>
        )}
      </div>
    </div>
  );
}
