import React from "react"
import PropTypes from "prop-types"
import VisuallyHidden from "@reach/visually-hidden"

const SIZES = {
  sm: "w-3 h-3",
  md: "w-5 h-5",
}

const STYLES = {
  sm: {
    padding: 2,
    width: 28
  },
  md: {
    padding: 2,
    width: 44
  }
}

const DISABLED_STYLES = {
  filter: "grayscale(100%)",
  cursor: "not-allowed",
  opacity: 0.75
}

function Toggle({ enabled, onClick, size = "md", ...props }) {
  const backgroundColor = enabled ? "bg-green-500" : "bg-gray-500"
  const thumbPosition = enabled ? "translate-x-full" : "translate-x-0"
  const activeStyle = props.disabled ? {...DISABLED_STYLES, ...STYLES[size]} : STYLES[size]
  const label = enabled ? "Disable" : "Enable"


  return (
    <button
      onClick={onClick}
      className={`inline-flex rounded-full transition-colors duration-200 focus:outline-none focus:shadow-outline ${backgroundColor}`}
      style={activeStyle}
      aria-checked={enabled}
      role="switch"
      {...props}
    >
      {/* Thumb */}
      <div
        className={`bg-white rounded-full transition-all duration-200 transform ${thumbPosition} ${SIZES[size]}`}
      />

      {/* A11y */}
      <VisuallyHidden>{label}</VisuallyHidden>
    </button>
  )
}

Toggle.propTypes = {
  enabled: PropTypes.bool.isRequired,
  onClick: PropTypes.func.isRequired,
  size: PropTypes.oneOf(["sm", "md"]),
  disabled: PropTypes.bool,
}

export default Toggle
