import type { Recipe, RecipeIngredient } from '@/lib/recipes';
import { buildTableLayout } from '@/lib/recipe-table-layout.mjs';

type Section = NonNullable<Recipe['tableFlow']>['sections'][number];
type Layout = ReturnType<typeof buildTableLayout>;

function quantityLabel(quantity: RecipeIngredient['quantity']) {
  if (!quantity) return '';
  if (quantity.text) return quantity.text;
  return [quantity.maxValue ? `${quantity.value}–${quantity.maxValue}` : quantity.value, quantity.unit].filter(Boolean).join(' ');
}

function SectionTable({ recipeTitle, section, layout, ingredients, actionLabels }: {
  recipeTitle: string;
  section: Section;
  layout: Layout;
  ingredients: Map<string, RecipeIngredient>;
  actionLabels: Map<string, string>;
}) {
  const labelOf = (row: { target: string; label: string | null }) => {
    const ingredient = ingredients.get(row.target);
    return row.label ?? (ingredient ? `${quantityLabel(ingredient.quantity)} ${ingredient.name}${ingredient.optional ? ' (fac.)' : ''}`.trim() : actionLabels.get(row.target) ?? row.target);
  };
  const startingAt = (row: number) => [
    ...layout.pads.filter((cell) => cell.row === row).map((cell) => ({ kind: 'pad' as const, ...cell })),
    ...layout.placed.filter((cell) => cell.row === row).map((cell) => ({ kind: 'action' as const, ...cell })),
  ].sort((a, b) => a.column - b.column);

  return <section className="recipe-table-section">
    <h2>{section.name}</h2>
    <div className="recipe-table-scroll" tabIndex={0} role="region" aria-label={`Table de préparation : ${section.name}`}>
      <div className="recipe-table-frame">
      <table className="recipe-flow-table">
        <caption className="sr-only">{recipeTitle} — {section.name}</caption>
        <colgroup><col className="recipe-flow-ingredient-column" />{Array.from({ length: layout.columns }, (_, index) => <col key={index} className="recipe-flow-action-column" />)}</colgroup>
        <tbody>
          {layout.setups.map((action) => <tr key={action.id} className="recipe-prep-banner"><td colSpan={layout.columns + 1}>{action.label}</td></tr>)}
          {layout.rows.map((entry, row) => <tr key={entry.id ?? entry.target}>
            <th scope="row" className="recipe-flow-source">{labelOf(entry)}</th>
            {startingAt(row).map((cell) => cell.kind === 'pad'
              ? <td key={`pad-${row}-${cell.column}`} rowSpan={cell.rowSpan} colSpan={cell.colSpan} aria-hidden="true" className="recipe-flow-pad" />
              : <td key={cell.action.id} rowSpan={cell.rowSpan} colSpan={cell.colSpan} className={`recipe-flow-action${cell.action.optional ? ' is-optional' : ''}`}>{cell.action.label}</td>)}
          </tr>)}
          {layout.asides.flatMap((action) => action.uses.map((key, index) => {
            const entry = layout.asideRows.find((row) => (row.id ?? row.target) === key)!;
            return <tr key={`${action.id}-${key}`} className="recipe-flow-aside">
              <th scope="row" className="recipe-flow-source">{labelOf(entry)}</th>
              {index === 0 && <td rowSpan={action.uses.length} colSpan={layout.columns} className="recipe-flow-action">{action.label}</td>}
            </tr>;
          }))}
        </tbody>
      </table>
      </div>
    </div>
  </section>;
}

export function RecipeTable({ recipe }: { recipe: Recipe }) {
  const ingredients = new Map(recipe.ingredients.flatMap((group) => group.items.map((ingredient) => [ingredient.id, ingredient] as const)));
  const actionLabels = new Map(recipe.tableFlow?.sections.flatMap((section) => section.actions.map((action) => [action.id, action.label] as const)) ?? []);
  const layouts = recipe.tableFlow?.sections.map((section) => ({ section, layout: buildTableLayout(section) })) ?? [];
  return <article className={`recipe-table-panel recipe-theme-${recipe.category}`}>
    <header className="recipe-table-header"><h1>{recipe.title}{recipe.yield && <small> ({recipe.yield.value}{recipe.yield.maxValue ? `–${recipe.yield.maxValue}` : ''} {recipe.yield.unit === 'servings' ? 'portions' : recipe.yield.unit})</small>}</h1></header>
    {recipe.tableFlow ? layouts.map(({ section, layout }) => <SectionTable key={section.id} recipeTitle={recipe.title} section={section} layout={layout} ingredients={ingredients} actionLabels={actionLabels} />)
      : <p className="recipe-table-notice">Le tableau de flux de cette recette n’est pas encore rédigé. Les instructions complètes sont dans l’onglet Fiche recette.</p>}
    {recipe.tableFlow && <footer className="recipe-table-context">
      {recipe.description && <p>{recipe.description}</p>}
      {recipe.tools.length > 0 && <section><h2>Matériel</h2><ul>{recipe.tools.map((tool) => <li key={tool.id}>{tool.name}{tool.optional && ' (facultatif)'}</li>)}</ul></section>}
      {recipe.notes.length > 0 && <section><h2>Notes</h2><ul>{recipe.notes.map((note, index) => <li key={index}>{note}</li>)}</ul></section>}
      {recipe.metadata.sources.length > 0 && <p className="recipe-source-links"><strong>Sources :</strong>{' '}{recipe.metadata.sources.map((source, index) => <span key={`${index}-${source.url ?? source.label}`}>{index > 0 && ' · '}{source.url ? <a href={source.url} target="_blank" rel="noreferrer">{source.label || source.url}</a> : source.label}</span>)}</p>}
    </footer>}
  </article>;
}
