import { useEffect, useState } from "preact/hooks";
import type { FunctionComponent } from "preact";
import { Loader } from "./loader.tsx";

interface IProps {
  packName: string;
}

export const PackInfo: FunctionComponent<IProps> = ({ packName }) => {
  const [showVersions, setShowVersions] = useState(false);
  const [packVersion, setPackVersion] = useState("");
  const [packVersionList, setPackVersionList] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [world, setWorld] = useState("");

  useEffect(() => {
    Promise.all([
      fetch("/api/pack/version").then((res) => res.text()).then((text) => {
        setPackVersion(text);
      }),
      fetch("/api/versions").then((res) => res.json()).then((json) => {
        setPackVersionList(json);
      }),
      fetch("/api/world").then((res) => res.text()).then((text) => {
        setWorld(text);
      }),
    ]).finally(() => setLoading(false));
  }, []);

  const updatePackVersion = async (version: string) => {
    const res = await fetch("/api/pack/version", {
      method: "POST",
      body: version,
    });

    if (res.status === 200) {
      setPackVersion(version);
    }
  };

  return (
    <>
      <h2 class="text-xl">{world} :: {packName}</h2>
      <p class="bg-lime-700 rounded-full shadow-md">
        {loading ? <Loader class="w-8" /> : (
          <>
            Datapack Version:{" "}
            <span
              class="relative cursor-pointer rounded-full bg-lime-200 text-black px-2 inline-block"
              onClick={() => setShowVersions(!showVersions)}
            >
              {packVersion}
              {showVersions && (
                <ul class="absolute top-full left-0 bg-lime-50 rounded-md shadow-md p-2 min-w 12">
                  {packVersionList.map((version) => (
                    <li onClick={() => updatePackVersion(version)}>
                      {version}
                    </li>
                  ))}
                </ul>
              )}
            </span>
          </>
        )}
      </p>
    </>
  );
};
