"use strict";

const React = require("react");

const defaultStyle = require("./style.css");
const useTheme = require("../../util/themeable");
const useID = require("../../util/use-id");
const contexts = require("../../contexts");
const composeHandlers = require("../../util/compose-handlers");
const generateGridItemStyle = require("../../util/generate-grid-item-style");

const Icon = require("../icon");

// FIXME: Mark div as button with aria attributes

module.exports = function Button({ x, y, id, type, onClick, children, icon, default: default_ }) {
	// TODO: Validate type?
	// TODO: How does icon + custom HTML children end up looking? Should we use a grid to ensure that the icon is always displayed on the left in its own column?
	let { withTheme } = useTheme({ control: "button", defaultStyle });
	let ownID = useID(id);
	let selectedID = React.useContext(contexts.button_selectedID);
	let capturedOnClick = React.useContext(contexts.button_onClick);

	React.useEffect(() => {
		if (capturedOnClick != null && default_ === true) {
			// This is a default selection in a choice list of some sort, eg. a button-set - so we simulate a click event.
			capturedOnClick(ownID);
		}
	}, [ capturedOnClick, ownID ]);

	let isSelected = (ownID === selectedID);

	let onClickAll = composeHandlers([
		capturedOnClick,
		onClick
	]);

	let typeClass = (type != null)
		? `type-${type}`
		: undefined;

	return (
		<div
			className={withTheme("uilibComponent", "button", typeClass, { selected: isSelected })}
			onClick={() => onClickAll(ownID)}
			style={generateGridItemStyle({ x, y })}
		>
			<span className={withTheme("buttonContents")}>
				{(icon != null)
					? <Icon icon={icon} />
					: null
				}

				<contexts.button_selectedID.Provider value={null}>
					{children}
				</contexts.button_selectedID.Provider>
			</span>
		</div>
	);
};
