import { useEffect, useState } from "preact/hooks";
import { AddToCart } from "../components/AddToCart";
import { pinProduct } from "../lib/api";
import { getConfig, text } from "../lib/config";
import { format } from "../lib/format";
import { groupStarts, specRows } from "../lib/rows";
import { CardRows } from "./CardRows";
import { CardStrip } from "./CardStrip";
import { useCardPages } from "./useCardPages";

/**
 * Phones and tablets: products side by side in `columns`, the base product
 * pinned in the first column, the others paged by swipe or ‹ ›. Pinning
 * another product saves it to the shopper's list (when the table shows it).
 */
export function MobileCards({ data, columns, onlyDiff, fromList }) {
  const { table, mobile = {} } = getConfig();
  const pinFirst = mobile.pin_first !== false && columns > 1;
  const [pinned, setPinned] = useState(data.pinned_id);

  useEffect(() => setPinned(data.pinned_id), [data.pinned_id]);

  const baseId = pinFirst ? pinned || data.products[0].id : null;
  const pager = useCardPages(data.products, baseId, columns);
  const rows = specRows(data, onlyDiff);

  const pin = (id) => {
    setPinned(id);
    if (fromList) {
      pinProduct(
        data.products.map((p) => p.id),
        id,
      ).catch(() => setPinned(data.pinned_id));
    }
  };

  return (
    <div
      className="pcfw-cards"
      style={{ "--pcfw-cols": pager.visible.length }}
      {...pager.swipe}
    >
      <div className="pcfw-cards__head">
        <CardStrip
          visible={pager.visible}
          base={pager.base}
          baseLabel={data.pinned_label}
          canPin={pinFirst}
          onPin={pin}
          canRemove={fromList}
        />
        {pager.pages > 1 && (
          <div className="pcfw-cards__nav">
            <button
              type="button"
              className="pcfw-cards__arrow"
              aria-label={text("prevProducts", "Previous products")}
              onClick={pager.prev}
            >
              ‹
            </button>
            <span className="pcfw-cards__pos" aria-live="polite">
              {format(
                text("pagePos", "%1$d of %2$d"),
                pager.page + 1,
                pager.pages,
              )}
            </span>
            <button
              type="button"
              className="pcfw-cards__arrow"
              aria-label={text("nextProducts", "Next products")}
              onClick={pager.next}
            >
              ›
            </button>
          </div>
        )}
      </div>
      <CardRows
        rows={rows}
        starts={groupStarts(data, rows)}
        visible={pager.visible}
        base={pager.base}
        emptyText={table.empty_cell_text ?? "—"}
        highlight={!onlyDiff && table.highlight_differences !== false}
      />
      {onlyDiff && !rows.length && (
        <p className="pcfw-cards__none">
          {text("noDifferences", "These products don't differ in any row.")}
        </p>
      )}
      <div className="pcfw-cards__foot">
        {pager.visible.map((p) => (
          <AddToCart key={p.id} cart={p.add_to_cart} />
        ))}
      </div>
    </div>
  );
}
