import React, { useRef, useState, useEffect } from 'react'
import { Button, ListBox, ListBoxItem, Popover, Select as AriaSelect, SelectValue } from 'react-aria-components'
import Icon from './Icon'
import './Select.scss'

const Select = ({
  items,
  selectedKey,
  onSelectionChange,
  isDisabled,
  placeholder,
  ariaLabel,
  ariaLabelledBy,
  ariaDescribedBy,
  isInvalid,
  className = '',
  triggerClassName = '',
  popoverClassName = '',
  optionClassName = '',
  portalSelector,
  renderItem,
}) => {
  const wrapperRef = useRef(null)
  const [portalContainer, setPortalContainer] = useState(null)

  useEffect(() => {
    if (!portalSelector || !wrapperRef.current) return
    setPortalContainer(wrapperRef.current.closest(portalSelector) || null)
  }, [portalSelector])

  return (
    <AriaSelect
      ref={wrapperRef}
      className={`select-field ${className}`}
      selectedKey={selectedKey}
      onSelectionChange={onSelectionChange}
      isDisabled={isDisabled}
      isInvalid={isInvalid}
      aria-label={ariaLabelledBy ? undefined : ariaLabel}
      aria-labelledby={ariaLabelledBy}
    >
      <Button type="button" className={`select-field-trigger ${triggerClassName}`} aria-describedby={ariaDescribedBy}>
        <SelectValue placeholder={placeholder}/>
        <Icon name="arrowDown.svg" width="10px" height="10px" ariaHidden="true"/>
      </Button>
      <Popover
        className={`select-field-popover ${popoverClassName}`}
        minWidth="trigger-width"
        UNSTABLE_portalContainer={portalContainer || undefined}
      >
        <ListBox className="select-field-listbox" items={items}>
          {(item) => (
            <ListBoxItem id={item.id} textValue={item.name} className={`select-field-option ${optionClassName}`}>
              {renderItem ? renderItem(item) : item.name}
            </ListBoxItem>
          )}
        </ListBox>
      </Popover>
    </AriaSelect>
  )
}

export default Select
