import {
  Select as AriaSelect,
  SelectValue,
  Popover,
  ListBox,
  Button,
} from 'react-aria-components'
import { cx } from 'class-variance-authority'

import { MaterialIcon } from '../Icons/MaterialIcon'
import { Typography } from '../Typography'
import { SelectItem } from './SelectItem'
import { SelectFilter } from './SelectFilter'

import type { SelectProps } from './types'

import styles from './select.module.css'

export function Select({
  name,
  label,
  items,
  isRequired,
  isDisabled,
  icon,
  itemIcon,
  enableFiltering,
}: SelectProps) {
  if (enableFiltering) {
    return (
      <SelectFilter
        name={name}
        label={label}
        items={items}
        isRequired={isRequired}
        isDisabled={isDisabled}
        icon={icon}
        itemIcon={itemIcon}
      />
    )
  }
  const iconColor = isDisabled ? 'Icon/Interactive/Disabled' : 'Icon/Default'

  return (
    <AriaSelect
      className={styles.select}
      name={name}
      aria-label={label}
      isRequired={isRequired}
      isDisabled={isDisabled}
    >
      <Button className={cx(styles.inner, styles.button)}>
        {icon ? (
          <MaterialIcon
            icon={icon}
            size={24}
            color={iconColor}
            aria-hidden="true"
          />
        ) : null}
        <SelectValue className={cx(styles.displayText, styles.selectValue)}>
          {({ isPlaceholder, selectedText }) => (
            <>
              <Typography
                variant={
                  isPlaceholder ? 'Body/Paragraph/mdRegular' : 'Label/xsRegular'
                }
              >
                <span className={styles.label}>{label}</span>
              </Typography>
              {selectedText ? (
                <Typography variant="Body/Paragraph/mdRegular">
                  <span>{selectedText}</span>
                </Typography>
              ) : null}
            </>
          )}
        </SelectValue>

        <MaterialIcon
          icon="chevron_right"
          size={24}
          color={iconColor}
          aria-hidden="true"
          className={styles.chevron}
        />
      </Button>

      <Popover className={styles.popover} shouldFlip={false}>
        <ListBox className={styles.listBox}>
          {items.map((item, idx) => (
            <Typography variant="Body/Paragraph/mdRegular" key={idx}>
              {typeof item === 'object' ? (
                <SelectItem
                  icon={item.icon || itemIcon}
                  isDisabled={item.isDisabled}
                >
                  {item.label}
                </SelectItem>
              ) : (
                <SelectItem icon={itemIcon} isDisabled={isDisabled}>
                  {item.toString()}
                </SelectItem>
              )}
            </Typography>
          ))}
        </ListBox>
      </Popover>
    </AriaSelect>
  )
}
