import { CompareIcon } from "@/lib/icons";
import { useState } from "react";
import { buttonLook } from "../lib/buttonLook";
import CheckboxPreview from "./CheckboxPreview";

/** Layout per style; "button" fills its column so long labels truncate. */
const CLASSES = {
  button:
    "ino:flex ino:h-9 ino:w-full ino:min-w-0 ino:cursor-pointer ino:items-center ino:justify-center ino:gap-1.5 ino:px-2 ino:text-[13px]",
  link: "ino:inline-flex ino:min-w-0 ino:cursor-pointer ino:items-center ino:gap-1.5 ino:self-start ino:p-0 ino:text-[13px] ino:underline",
  icon: "ino:flex ino:size-9 ino:cursor-pointer ino:items-center ino:justify-center ino:self-start ino:p-0",
};

/**
 * The Compare button as shoppers will see it, in normal, hover, added and
 * "remove on hover" states, using the unsaved draft.
 */
const PreviewButton = ({ design, button, labels, added, name, onToggle }) => {
  const [hover, setHover] = useState(false);
  const state = added ? "added" : hover ? "hover" : "normal";
  const look = buttonLook(design, button.style, state);
  const removing = added && hover && button.remove_on_second_click;
  const label = removing ? labels.remove : added ? labels.added : labels.add;
  const icon = added ? (removing ? "close" : "check") : button.icon;
  // As on the storefront: own style only (not theme, not link); "Icon when
  // added" on the ✓, "Icon" otherwise ("inherit" follows the text).
  const own = !design.button.inherit_theme && button.style !== "link";
  const iconColor = !own
    ? "currentColor"
    : added && !removing
      ? design.button.icon_added
      : design.button.icon && design.button.icon !== "inherit"
        ? design.button.icon
        : "currentColor";
  const iconOnly = button.style === "icon";

  if (button.style === "checkbox") {
    return (
      <CheckboxPreview
        added={added}
        label={labels.add}
        color={design.button.added_border}
        onToggle={onToggle}
      />
    );
  }

  return (
    <button
      type="button"
      aria-pressed={added}
      aria-label={iconOnly ? `${label} ${name}` : undefined}
      onClick={onToggle}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={look}
      className={CLASSES[button.style] ?? CLASSES.button}
    >
      {button.icon !== "none" || added ? (
        <span
          style={{ color: iconColor }}
          className="ino:inline-flex ino:shrink-0"
        >
          <CompareIcon name={icon} size={15} />
        </span>
      ) : null}
      {!iconOnly && <span className="ino:truncate">{label}</span>}
    </button>
  );
};

export default PreviewButton;
