import React from 'react'

import PropTypes from 'prop-types'
import { componentPropType } from '../utils/props/componentPropType'
import { selectSystemProps } from '../utils/props/selectSystemProps'
import { htmlAttrs } from '../utils/htmlAttrs'

const [selectProps, selectedSystemPropTypes] = selectSystemProps([htmlAttrs])

export const Picker = React.forwardRef(
  (
    {
      value,
      onChange,
      onFocus,
      onBlur,
      onMouseOver,
      onMouseOut,
      onOpen = () => {},
      onClose = () => {},
      style,
      inactive,
      children,
      placeholder,
      nativeID,
      testID,
      ...rest
    },
    ref
  ) => {
    const selectedProps = selectProps(rest)
    const { accessibilityLabel, accessibilityDescribedBy, accessibilityInvalid } = rest

    return (
      /**
       * The onOpen and onClose methods are to call the new active variant that changes the icon of the select,
       * onOpen when the select is open and onClose when the select is closed, onOpen is in the event onMousedown
       * when is selected and oClose is in onMouseOut and onChange when the select is closed.
       */
      <select
        ref={ref}
        style={style}
        onMouseOver={onMouseOver}
        onMouseOut={() => {
          onMouseOut?.()
          onClose?.()
        }}
        onFocus={onFocus}
        onBlur={onBlur}
        onMouseDown={onOpen}
        disabled={inactive}
        value={value || (placeholder !== undefined ? placeholder.value : undefined)}
        onChange={(event) => {
          onClose()
          onChange(event.target.value, event)
        }}
        id={nativeID}
        aria-label={accessibilityLabel}
        aria-describedby={accessibilityDescribedBy}
        aria-invalid={accessibilityInvalid}
        data-testid={testID}
        {...selectedProps}
      >
        {placeholder !== undefined && (
          <option value={placeholder.value} disabled hidden>
            {placeholder.label}
          </option>
        )}
        {children}
      </select>
    )
  }
)
Picker.displayName = 'SelectPicker'

Picker.propTypes = {
  ...selectedSystemPropTypes,
  value: PropTypes.string,
  onChange: PropTypes.func,
  onFocus: PropTypes.func,
  onBlur: PropTypes.func,
  onMouseOver: PropTypes.func,
  onMouseOut: PropTypes.func,
  /**
   * It executes when the select choices are open
   */
  onOpen: PropTypes.func,
  /**
   * It executes when the select choices are closed
   */
  onClose: PropTypes.func,
  style: PropTypes.object,
  inactive: PropTypes.bool,
  children: componentPropType(['Item', 'Group']),
  placeholder: PropTypes.shape({
    value: PropTypes.string,
    label: PropTypes.string
  }),
  nativeID: PropTypes.string,
  testID: PropTypes.string
}
