import type { Accessor } from "solid-js";
import { createMemo } from "solid-js";
import type { BaseOption, BentoSelection } from "@ben-to/builder/domain";
import {
  baseFlavorGroupKey,
  baseIdsInSameFlavorGroup,
  computeRecipeSteps
} from "@ben-to/builder/domain";
import type { RecipesIndex } from "@ben-to/recipes/catalog";
import type { LocaleCode } from "@ben-to/i18n/dictionary";
import type { FlavorFilter } from "./builder-flow-types";

export function useBuilderCatalog(props: {
  readonly recipesIndex: Accessor<RecipesIndex | undefined>;
  readonly selection: Accessor<BentoSelection>;
  readonly flavorFilter: Accessor<FlavorFilter>;
  readonly locale: Accessor<LocaleCode>;
}) {
  const filteredBases = createMemo(() => {
    const index = props.recipesIndex();
    if (!index) return [];
    if (props.flavorFilter() !== "all") {
      return index.bases.filter((base) => base.flavor === props.flavorFilter());
    }
    const seen = new Set<string>();
    const out: BaseOption[] = [];
    for (const base of index.bases) {
      const key = baseFlavorGroupKey(base);
      if (seen.has(key)) continue;
      seen.add(key);
      out.push(base);
    }
    return out;
  });

  const currentBase = createMemo(() =>
    props.recipesIndex()?.bases.find((base) => base.id === props.selection().baseId)
  );

  const availableVariants = createMemo(() => {
    const index = props.recipesIndex();
    if (!index) return [];
    const baseId = props.selection().baseId;
    if (!baseId) {
      return [...(index.variants ?? [])];
    }
    const groupIds = baseIdsInSameFlavorGroup(index.bases, baseId);
    return (index.variants ?? []).filter((variant) => variant.baseIds.some((id) => groupIds.includes(id)));
  });

  const currentVariant = createMemo(() =>
    (props.recipesIndex()?.variants ?? []).find((variant) => variant.id === props.selection().variantId)
  );

  const mergedRecipe = createMemo(() =>
    computeRecipeSteps({
      base: currentBase() ?? null,
      variant: currentVariant() ?? null
    })
  );

  const recipeCoverImageUrl = createMemo(() => currentVariant()?.recipeCoverImageUrl ?? null);

  const recipeDisplayTitle = createMemo(() => {
    const base = currentBase();
    const variant = currentVariant();
    const loc = props.locale();
    if (base && variant) return `${base.name[loc]} — ${variant.name[loc]}`;
    if (variant) return variant.name[loc];
    if (base) return base.name[loc];
    return "";
  });

  return {
    filteredBases,
    currentBase,
    availableVariants,
    currentVariant,
    mergedRecipe,
    recipeCoverImageUrl,
    recipeDisplayTitle
  };
}
