import { memo } from 'react'

import { styled } from '../core'
import { List } from '../list'
import { Popover } from '../popover'
import { cs } from '../utils'
import { AutoCompletePopoverProps } from './input.types'

const InputContainer = styled.divBox`
  width: 100%;
`

const options = {
  aria: {
    expanded: false,
  },
}

/** Wrapper for the autocomplete popover. */
export const AutoCompletePopover = ({
  autoCompleteOptions,
  autoCompleteMaxHeight,
  children,
  filterAutoCompleteOptions,
  onAutoCompleteSelect,
}: AutoCompletePopoverProps) => {
  if (autoCompleteOptions === undefined) return children

  return (
    <Popover options={options} placement="bottom-start">
      <Popover.Trigger as={InputContainer} className={cs('vui-input-popoverTrigger')}>
        {children}
      </Popover.Trigger>
      {!!autoCompleteOptions && (
        <Popover.Content>
          <List maxH={autoCompleteMaxHeight}>
            {autoCompleteOptions?.filter?.(filterAutoCompleteOptions).map((i: string) => (
              <List.Item cursor="pointer" hoverBg="skyBlue.hover" key={i} onClick={() => onAutoCompleteSelect(i)}>
                {i}
              </List.Item>
            ))}
          </List>
        </Popover.Content>
      )}
    </Popover>
  )
}

export default memo(AutoCompletePopover)
