import type { SourceView } from "@batch-cooking/shared";
import { useEffect, useState } from "react";
import { apiClient } from "../../../api/client";

export type EnabledSourcesState =
  | { status: "loading" }
  | { status: "loaded"; sources: SourceView[] }
  | { status: "error" };

/**
 * Which sources exist, crossed with which the household has enabled
 * (`/parametres/foyer`) — shared by `RecipesPage` and `RecipePickerDialog`,
 * both of which need this to render one `RecipeTabs` tab per enabled
 * source (see `RecipeTabs`' own doc comment). Loaded once per mount, not
 * re-fetched on every render — a household's enabled sources only change
 * from the settings page, never from here.
 */
export function useEnabledSources(): EnabledSourcesState {
  const [state, setState] = useState<EnabledSourcesState>({ status: "loading" });

  useEffect(() => {
    let cancelled = false;
    Promise.all([apiClient.getSources(), apiClient.getHouseSourceIds()])
      .then(([sources, enabledIds]) => {
        if (cancelled) return;
        setState({
          status: "loaded",
          sources: sources.filter((source) => enabledIds.includes(source.id)),
        });
      })
      .catch(() => {
        if (!cancelled) setState({ status: "error" });
      });
    return () => {
      cancelled = true;
    };
  }, []);

  return state;
}
