import React, { useRef, useState, useEffect } from 'react'
import { Button, FieldError, Label, ListBox, ListBoxItem, Popover, Select, SelectValue } from 'react-aria-components'
import { Icon } from '$core-components'
import './Dropdown.scss'

const Dropdown = ({ error, isRequired, label, items, placeholder, renderItem, ...forwardedProps }) => {
  const selectRef = useRef(null)
  const [portalContainer, setPortalContainer] = useState(null)
  const { onSelectionChange, onChange, ...restProps } = forwardedProps
  const handleChange = onChange || onSelectionChange

  useEffect(() => {
    if (!selectRef.current) return
    const modalContainer = selectRef.current.closest('.address-modal, .modal, [role="dialog"]')
    setPortalContainer(modalContainer || (typeof document !== 'undefined' ? document.body : null))
  }, [])

  return (
    <Select
      {...restProps}
      items={items}
      className={`dropdown-field ${error ? 'dropdown-field-invalid' : ''} ${isRequired ? 'dropdown-field-required' : ''}`}
      isInvalid={error}
      isRequired={isRequired}
      validationBehavior="aria"
      ref={selectRef}
      onSelectionChange={(key) => handleChange?.(key)}
    >
      <Label className="dropdown-field-label">{label}:</Label>
      <Button className="dropdown-field-select">
        <SelectValue placeholder={placeholder} />
        <Icon
          name={'arrowDown.svg'}
          width='10px'
          height='10px'
        />
      </Button>
      <Popover
        className="dropdown-field-popover"
        minWidth="trigger-width"
        UNSTABLE_portalContainer={portalContainer || (typeof document !== 'undefined' ? document.body : null)}
      >
        <ListBox
          items={items}
          className="dropdown-field-listbox"
          selectionMode="single"
        >
          {(item) => (
            <ListBoxItem
              key={item.id}
              id={item.id}
              textValue={item.name || item.value || item.label}
              className="dropdown-field-option"
            >
              {renderItem ? renderItem(item) : (item.name || item.value || item.label)}
            </ListBoxItem>
          )}
        </ListBox>
      </Popover>
      <FieldError className="form-field-error">{error}</FieldError>
    </Select>
  )
}

export default Dropdown

