import React, { useState, createContext } from "react"
import PropTypes from "prop-types"
import cx from "classnames"

const HORIZONTAL_SIZES = {
  sm: "text-xs h-8",
  md: "text-sm h-10",
  lg: "text-sm h-12",
}

const VERTICAL_SIZES = {
  sm: "text-xs",
  md: "text-sm",
  lg: "text-sm",
}

export const ButtonGroupContext = createContext({})

function ButtonGroup({
  children,
  className,
  spacing = 1,
  orientation = "horizontal",
  size = "md",
  ...props
}) {
  const [activeId, setActiveId] = useState(null)

  const classes = cx(
    "inline-grid auto-cols-fr auto-rows-fr border border-solid border-gray-200 items-center rounded overflow-hidden",
    className,
    `gap-${spacing} p-${spacing}`,
    {
      "grid-flow-col": orientation === "horizontal",
      "grid-flow-row": orientation === "vertical",
      [HORIZONTAL_SIZES[size]]: orientation === "horizontal",
      [VERTICAL_SIZES[size]]: orientation === "vertical",
    }
  )

  const contextValue = {
    present: true,
    groupSize: `${orientation}-${size}`,
    activeId, setActiveId,
    orientation
  }

  return (
    <div {...props} className={classes} data-testid="btn-group" role="group">
      <ButtonGroupContext.Provider value={contextValue}>
        {children}
      </ButtonGroupContext.Provider>
    </div>
  )
}

export default ButtonGroup

ButtonGroup.propTypes = {
  spacing: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  orientation: PropTypes.oneOf(["horizontal", "vertical"]),
  size: PropTypes.oneOf(Object.keys(HORIZONTAL_SIZES)),
  className: PropTypes.string,
  children: PropTypes.node,
}
