import type { BrowsableSourceItemView } from "@batch-cooking/shared";
import { useTranslation } from "react-i18next";
import "./recipes.scss";

/**
 * List of one source's browsable items (`RecipeSourcesPanel`) — same
 * "photo + name, click/Enter to select" row shape as `RecipeTable`, plus
 * an "already imported" badge in place of allergen/regime columns (a
 * source item has neither, it's not resolved against our catalogs until
 * previewed).
 */
export function SourceItemTable({
  items,
  selectedExternalId,
  onSelect,
}: {
  items: BrowsableSourceItemView[];
  selectedExternalId: string | null;
  onSelect: (item: BrowsableSourceItemView) => void;
}) {
  const { t } = useTranslation();

  return (
    <div className="recipe-table-wrap">
      <table className="recipe-table">
        <thead>
          <tr>
            <th />
            <th>{t("recipes.table.name")}</th>
            <th />
          </tr>
        </thead>
        <tbody>
          {items.map((item) => (
            <tr
              key={item.externalId}
              className={item.externalId === selectedExternalId ? "selected" : undefined}
              onClick={() => onSelect(item)}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  onSelect(item);
                }
              }}
              tabIndex={0}
              aria-current={item.externalId === selectedExternalId ? "true" : undefined}
            >
              <td>
                <span className="recipe-table__photo" aria-hidden="true">
                  {item.picture ? <img src={item.picture} alt="" /> : "🍽️"}
                </span>
              </td>
              <td className="recipe-table__name">{item.title}</td>
              <td>
                {item.alreadyImported && (
                  <span className="source-item-table__imported-badge">
                    {t("recipes.sources.alreadyImported")}
                  </span>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
