import type { Accessor } from "solid-js";
import { For, Show } from "solid-js";
import type { StepKind } from "@ben-to/builder/domain";
import { computeRecipeSteps } from "@ben-to/builder/domain";
import type { LocaleCode } from "@ben-to/i18n/dictionary";
import type { DictionaryView } from "./dictionary-view";
import { fillRecipeTemplate } from "./recipe-template";
import { SpriteTile } from "./SpriteTile";
import { publicAssetHref } from "./public-asset";
import type { RecipeSheetHandle } from "./use-recipe-sheet";

type MergedRecipeView = ReturnType<typeof computeRecipeSteps>;

export function RecipeSheetSection(props: {
  readonly currentStep: Accessor<StepKind>;
  readonly locale: Accessor<LocaleCode>;
  readonly t: Accessor<DictionaryView>;
  readonly recipeCoverImageUrl: Accessor<string | null>;
  readonly recipeDisplayTitle: Accessor<string>;
  readonly mergedRecipe: Accessor<MergedRecipeView>;
  readonly recipe: RecipeSheetHandle;
}) {
  const r = props.recipe;
  return (
    <Show when={props.currentStep() === "recipe"}>
      <div
        class="recipe-scroll"
        ref={(el) => {
          r.bindRecipeScrollHost(el);
        }}
        onScroll={r.onRecipeScroll}
      >
        <section class="recipe-sheet" aria-labelledby="recipe-sheet-title">
          <Show when={props.recipeCoverImageUrl()}>
            <div class="recipe-sheet__hero">
              <div class="recipe-sheet__hero-media">
                <img
                  class="recipe-sheet__photo"
                  src={publicAssetHref(props.recipeCoverImageUrl())}
                  alt={props.recipeDisplayTitle() || props.t().recipe}
                  width="1200"
                  height="675"
                  decoding="async"
                  fetchpriority="high"
                />
              </div>
            </div>
          </Show>

          <h2 class="recipe-sheet__title" id="recipe-sheet-title">
            {props.recipeDisplayTitle() || props.t().recipe}
          </h2>

          <div class="recipe-sheet__actions">
            <button type="button" class="recipe-sheet__action" onClick={() => void r.shareRecipe()}>
              {props.t().shareRecipe}
            </button>
            <button type="button" class="recipe-sheet__action" onClick={r.printRecipe}>
              {props.t().printRecipe}
            </button>
          </div>

          <Show when={r.shareFeedback()}>
            <p class="recipe-sheet__share-feedback" role="status" aria-live="polite">
              {r.shareFeedback()}
            </p>
          </Show>

          <div class="servings-stepper" role="group" aria-label={props.t().servings}>
            <button
              type="button"
              class="servings-stepper__btn"
              aria-label={props.t().decreaseServings}
              disabled={r.servings() <= 1}
              onClick={() => r.bumpServings(-1)}
            >
              −
            </button>
            <label class="servings-stepper__field">
              <span class="visually-hidden">{props.t().servings}</span>
              <input
                class="servings-stepper__input"
                type="text"
                inputMode="numeric"
                autocomplete="off"
                maxLength={2}
                value={r.servingsFieldValue()}
                onFocus={r.onServingsFocus}
                onInput={r.onServingsInput}
                onBlur={r.onServingsBlur}
              />
            </label>
            <button
              type="button"
              class="servings-stepper__btn"
              aria-label={props.t().increaseServings}
              disabled={r.servings() >= 99}
              onClick={() => r.bumpServings(1)}
            >
              +
            </button>
          </div>

          <p class="recipe-sheet__print-servings" aria-hidden="true">
            {props.t().servings}: {r.servings()}
          </p>

          <h3 class="recipe-sheet__subtitle">{props.t().ingredients}</h3>
          <ul class="recipe-sheet__ingredient-list">
            <For each={r.displayedIngredients()}>
              {(ingredient) => (
                <li class="recipe-sheet__ingredient-item">
                  <button
                    type="button"
                    class="recipe-sheet__ingredient-row"
                    classList={{
                      "recipe-sheet__ingredient-row--done": r.checkedIngredientIds().has(ingredient.id)
                    }}
                    aria-pressed={r.checkedIngredientIds().has(ingredient.id)}
                    title={[
                      fillRecipeTemplate(props.t().recipeIngredientCheckboxLabel, {
                        name: ingredient.name[props.locale()]
                      }),
                      String(ingredient.info[props.locale()] ?? "").trim()
                    ]
                      .filter(Boolean)
                      .join(" — ")}
                    onClick={() => r.toggleIngredientChecklist(ingredient.id)}
                  >
                    <span class="recipe-sheet__ingredient-media" aria-hidden="true">
                      {ingredient.coverSprite ? (
                        <SpriteTile
                          sprite={ingredient.coverSprite}
                          size={32}
                          class="recipe-sheet__ingredient-sprite"
                        />
                      ) : (
                        <img
                          class="recipe-sheet__ingredient-fallback"
                          src={publicAssetHref("/ingredient-unknown.png")}
                          width="32"
                          height="32"
                          alt=""
                          decoding="async"
                        />
                      )}
                    </span>
                    <span class="recipe-sheet__ingredient-text">
                      <strong>
                        {ingredient.quantity}
                        {ingredient.unit ? ` ${ingredient.unit}` : ""}
                      </strong>{" "}
                      {ingredient.name[props.locale()]}
                    </span>
                    <span class="recipe-sheet__ingredient-row-check" aria-hidden="true">
                      <span class="recipe-sheet__ingredient-mark__glyph">✓</span>
                    </span>
                  </button>
                </li>
              )}
            </For>
          </ul>
          <h3 class="recipe-sheet__subtitle">{props.t().steps}</h3>
          <ol class="recipe-sheet__steps-list">
            <For each={props.mergedRecipe().steps}>
              {(step, index) => (
                <li class="recipe-sheet__step-item">
                  <button
                    type="button"
                    class="recipe-sheet__step-btn"
                    classList={{
                      "recipe-sheet__step-btn--done": r.doneStepIds().has(step.id)
                    }}
                    aria-pressed={r.doneStepIds().has(step.id)}
                    title={fillRecipeTemplate(props.t().recipeStepToggleLabel, {
                      n: index() + 1
                    })}
                    onClick={() => r.toggleStepChecklist(step.id)}
                  >
                    {step.text[props.locale()]}
                  </button>
                </li>
              )}
            </For>
          </ol>
        </section>
      </div>
    </Show>
  );
}
