import React, { useContext } from "react"
import PropTypes from "prop-types"
import {
  useListItem,
} from "@floating-ui/react"
import cx from "classnames"
import Icon from "../icon"
import { SelectContext } from "./select"

export default function Option({ children, label, disabled, create, ...props }) {
  const {
    activeIndex,
    selectedIndex,
    getItemProps,
    handleSelect
  } = useContext(SelectContext)

  const content = label || children
  const { ref, index } = useListItem({ label: disabled ? null : content })

  const isActive = activeIndex === index
  const isSelected = index >= 0 ? selectedIndex === index : false

  return (
    <button
      ref={ref}
      {...props}
      role="option"
      aria-selected={isSelected}
      aria-disabled={disabled}
      tabIndex={isActive && !disabled ? 0 : -1}
      data-index={index}
      className={cx("flex items-center gap-1 justify-between w-full p-2 text-left text-sm focus:outline-none", props.className, {
        "relative border-t border-gray-200 pt-4 px-4 mt-2": create,
        "rounded": !create,
        "text-gray-900": !disabled,
        "bg-gray-50": isActive && !disabled && !create,
        "text-gray-500 cursor-default": disabled,
      })}
      style={create ? { left: -8, width: "calc(100% + 16px)" } : {}}
      {...getItemProps({
        onClick: () => {
          if(disabled) return
          handleSelect(index)
        }
      })}
    >
      <span className="flex-1">{children}</span>
      {isSelected && <Icon name="check" aria-hidden="true" />}
    </button>
  )
}

Option.propTypes = {
  children: PropTypes.node,
  disabled: PropTypes.bool,
  selected: PropTypes.bool,
  filtrable: PropTypes.bool,
  className: PropTypes.string,
  create: PropTypes.bool,
  label: PropTypes.node,
}