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

/**
 * Remove button on a product card (the shopper's own list only). The
 * cards refetch through the `pcfw:removed` event; on failure the button
 * becomes clickable again.
 */
export function CardRemove({ product }) {
  const [busy, setBusy] = useState(false);

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

  return (
    <button
      type="button"
      className="pcfw-cards__remove"
      aria-label={format(
        text("removeItem", "Remove %s"),
        plainText(product.name),
      )}
      disabled={busy}
      onClick={remove}
    >
      <CloseIcon size={12} />
    </button>
  );
}
