import React, { useState, useContext } from "react"
import cx from "classnames"
import PropTypes from "prop-types"
import VisuallyHidden from "@reach/visually-hidden"
import CKIcon from "../ck-icon"
import Button, { TOKENS } from "."
import { ButtonGroupContext } from "./button-group"

const DEFAULT = "border border-solid border-transparent focus:outline-none"

const SIZES = {
  md: "text-base p-2 rounded",
}

/**
 * @param {Object} props
 * @param {"primary"|"secondary"|"tertiary"|"plain"} props.is
 * @param {"sm"|"md"|"lg"} props.size
 * @param {string} props.icon
 * @param props.label A11y label
 * @param className any custom classes to be applied to button
 */
const IconButton = React.forwardRef(
  (
    {
      is = "secondary",
      size = "md",
      icon,
      label,
      disabled,
      className,
      onMouseDown = () => {},
      onBlur = () => {},
      ...props
    },
    ref
  ) => {
    const [clicked, setClicked] = useState(false)
    const groupContext = useContext(ButtonGroupContext)

    const classes = cx(
      className,
      disabled ? "cursor-default" : "cursor-pointer",
      {
        [DEFAULT]: Object.keys(TOKENS).includes(is) || disabled,
        [SIZES[size]]: Object.keys(TOKENS).includes(is) || disabled,
        [TOKENS[is]]: !disabled,
        "rounded": is || disabled,
        "text-gray-600 bg-gray-200": disabled,
        "focus:outline-blue": !clicked,
        "inline-block": props.href,
        "inline-flex items-center justify-center align-middle": Boolean(icon),
        "rounded-none border-none": groupContext.present
      }
    )

    const handleMouseDown = (event) => {
      setClicked(true)
      onMouseDown(event)
    }

    const handleBlur = (event) => {
      setClicked(false)
      onBlur(event)
    }

    return (
      <Button
        {...props}
        ref={ref}
        className={classes}
        onMouseDown={handleMouseDown}
        onBlur={handleBlur}
        disabled={disabled}
      >
        <VisuallyHidden>{label}</VisuallyHidden>
        <CKIcon name={icon} className="pointer-events-none" />
      </Button>
    )
  }
)

IconButton.propTypes = {
  icon: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  ...Button?.propTypes,
}

export default IconButton
