import { MenuEntry } from "@islands/KMenu/types.ts";
import { TMDBSeries } from "@lib/types.ts";
import { debounce } from "@lib/helpers.ts";
import { Series } from "@lib/resource/series.ts";
import { getCookie } from "@lib/string.ts";

export const createNewSeries: MenuEntry = {
  title: "Create new series",
  meta: "",
  icon: "IconSquareRoundedPlus",
  cb: (state) => {
    state.menus["input_link"] = {
      title: "Search",
      entries: [],
    };

    state.menus["loading"] = {
      title: "Search",
      entries: [
        {
          title: "Loading",
          icon: "IconLoader2",
          cb() {
          },
        },
      ],
    };

    state.activeMenu.value = "input_link";
    state.activeState.value = "normal";

    let currentQuery: string;
    const search = debounce(async function search(query: string) {
      currentQuery = query;
      if (query.length < 2) {
        return;
      }

      const response = await fetch(
        "/api/tmdb/query?q=" + query + "&type=series",
      );

      const series = await response.json() as TMDBSeries[];

      if (query !== currentQuery) return;

      state.menus["input_link"] = {
        title: "Search",
        entries: series.map((r) => {
          return {
            title: `${r.name} - ${r.first_air_date}`,
            cb: async () => {
              state.activeState.value = "loading";
              const response = await fetch("/api/series/" + r.id, {
                method: "POST",
              });
              const series = await response.json() as Series;
              unsub();
              window.location.href = "/series/" + series.name;
            },
          };
        }),
      };
      state.commandInput.value = "";
      state.activeMenu.value = "input_link";
    }, 500);

    const unsub = state.commandInput.subscribe((value) => {
      state.activeMenu.value = "loading";
      search(value);
    });
  },
  visible: () => {
    if (!getCookie("session_cookie")) return false;
    if (
      !globalThis?.location?.pathname?.includes("series") &&
      globalThis?.location?.pathname !== "/"
    ) return false;
    return true;
  },
};
