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

export const PacksList = (
  { setPackName }: { setPackName: Dispatch<StateUpdater<string>> },
) => {
  const [packs, setPacks] = useState<{ name: string; path: string }[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/packs").then((res) => res.json()).then((json) => {
      setPacks(json);
    }).finally(() => setLoading(false));
  }, []);

  const setPackNameThing = async (name: string) => {
    setLoading(true);
    const body = new FormData();
    body.set("packName", name);
    const res = await fetch("/api/pack", {
      method: "POST",
      body,
    });

    const json = await res.json();

    if (res.status === 200) {
      document.title = json.packName;
      setPackName(json.packName);
    }
    setLoading(false);
  };

  return loading ? <Loader /> : (
    <ul>
      {packs.length
        ? packs.map((pack) => (
          <li
            class="cursor-pointer even:bg-black/5"
            onClick={() => setPackNameThing(pack.name)}
          >
            {pack.name}
          </li>
        ))
        : <li>No packs found</li>}
    </ul>
  );
};
