import { useState } from "preact/hooks";
import { removeFromList } from "../lib/api";
import { text } from "../lib/config";
import { format } from "../lib/format";
import { plainText } from "../lib/plain";
import { CloseIcon, PinIcon } from "./icons";

/**
 * Pin and Remove buttons on a product's image (the shopper's own list
 * only). Pinning toggles the base product; removing refetches the table
 * through the `pcfw:removed` event.
 */
export function HeadActions({ product, pinned, onPin }) {
  const [busy, setBusy] = useState(false);
  const name = plainText(product.name);

  const remove = async () => {
    setBusy(true);
    if (!(await removeFromList(product.id))) {
      setBusy(false);
    }
  };

  return (
    <div className="pcfw-table__actions">
      <button
        type="button"
        className="pcfw-table__action"
        aria-pressed={pinned ? "true" : "false"}
        aria-label={format(
          pinned
            ? text("unpinItem", "Unpin %s")
            : text("pinItem", "Pin %s as the base product"),
          name,
        )}
        onClick={() => onPin(pinned ? null : product.id)}
      >
        <PinIcon size={15} />
      </button>
      <button
        type="button"
        className="pcfw-table__action"
        aria-label={format(text("removeItem", "Remove %s"), name)}
        disabled={busy}
        onClick={remove}
      >
        <CloseIcon size={14} />
      </button>
    </div>
  );
}
