import { CATEGORY_LABELS, WAFFLE_CATEGORIES } from "@/lib/constants";
import type { CustomWaffleConfig, IngredientPickerItem } from "@/lib/custom-waffle";
import { CustomWaffleCard } from "./CustomWaffleCard";
import type { Waffle } from "@/generated/prisma/client";
import {
  WaffleIngredientList,
  type MenuIngredient,
} from "./WaffleIngredientList";
import { WaffleMenuImage } from "./WaffleMenuImage";

export type WaffleForMenu = Waffle & {
  ingredientItems: MenuIngredient[];
};

const CATEGORY_ORDER = ["DU_MOIS", "SUCREE", "SALEE"] as const;

function sortWaffles(waffles: WaffleForMenu[]) {
  const rank = (c: string) => {
    const i = CATEGORY_ORDER.indexOf(c as (typeof CATEGORY_ORDER)[number]);
    return i === -1 ? 99 : i;
  };
  return [...waffles].sort(
    (a, b) => rank(a.category) - rank(b.category) || a.name.localeCompare(b.name)
  );
}

function groupByCategory(waffles: WaffleForMenu[]) {
  const map = new Map<string, WaffleForMenu[]>();
  for (const w of sortWaffles(waffles)) {
    const list = map.get(w.category) ?? [];
    list.push(w);
    map.set(w.category, list);
  }
  return map;
}

export function MenuSection({
  waffles,
  intro,
  ingredientCatalog,
  customWaffle,
}: {
  waffles: WaffleForMenu[];
  intro: string;
  ingredientCatalog: IngredientPickerItem[];
  customWaffle: CustomWaffleConfig;
}) {
  const grouped = groupByCategory(waffles);

  return (
    <section id="menu" className="scroll-mt-24 px-4 py-20 sm:px-6">
      <div className="mx-auto max-w-6xl">
        <div className="mb-12 text-center">
          <h2 className="text-3xl font-bold text-chocolat sm:text-4xl">Menu</h2>
          {intro.trim() ? (
            <p className="mt-3 text-muted">{intro}</p>
          ) : null}
        </div>

        <div className="flex flex-col gap-16">
          {CATEGORY_ORDER.map((key) => {
            const items = grouped.get(key) ?? [];
            const showCustomWaffle =
              key === WAFFLE_CATEGORIES.DU_MOIS && customWaffle.visible;
            if (!items.length && !showCustomWaffle) return null;
            return (
              <div key={key}>
                <h3 className="mb-6 flex items-center gap-3 text-xl font-bold text-chocolat">
                  <span className="h-1 w-10 rounded-full bg-gaufre" />
                  {CATEGORY_LABELS[key] ?? key}
                </h3>
                <ul className="grid gap-6 sm:grid-cols-2">
                  {showCustomWaffle ? (
                    <CustomWaffleCard
                      config={customWaffle}
                      ingredients={ingredientCatalog}
                    />
                  ) : null}
                  {items.map((w) => (
                    <li
                      key={w.id}
                      className="overflow-hidden rounded-3xl border border-chocolat/10 bg-white shadow-[0_8px_30px_-8px_rgba(61,43,31,0.12)] transition hover:shadow-[0_12px_40px_-8px_rgba(61,43,31,0.18)]"
                    >
                      {w.imageUrl ? (
                        <div className="relative aspect-[16/10] w-full bg-chocolat/5">
                          <WaffleMenuImage src={w.imageUrl} alt={w.name} />
                        </div>
                      ) : null}
                      <div className="p-6">
                        <div className="mb-2 flex flex-wrap items-start justify-between gap-2">
                          <span className="font-semibold text-chocolat">
                            {w.name}
                          </span>
                          <div className="flex items-center gap-2">
                            {w.isNew && (
                              <span className="rounded-full bg-gaufre/20 px-2.5 py-0.5 text-xs font-bold uppercase tracking-wide text-chocolat">
                                Nouveauté
                              </span>
                            )}
                            <span className="whitespace-nowrap text-lg font-bold text-gaufre">
                              {w.price.toFixed(2).replace(".", ",")} €
                            </span>
                          </div>
                        </div>
                        <p className="text-sm leading-relaxed text-muted">
                          {w.ingredients}
                        </p>
                        <WaffleIngredientList items={w.ingredientItems} />
                      </div>
                    </li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
