"use client"
import { useRef } from "react"
import {
  Button,
  type Key,
  Label,
  ListBox,
  ListBoxItem,
  Popover,
  Select as ReactAriaSelect,
  SelectValue,
} from "react-aria-components"

import SelectChevron from "../../SelectChevron"

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

import type { SelectProps } from "./select"

export default function Select({
  "aria-label": ariaLabel,
  items,
  label,
  name,
  onSelect,
  placeholder,
  value,
}: SelectProps) {
  const divRef = useRef<HTMLDivElement>(null)

  function handleOnSelect(key: Key) {
    onSelect(key, name)
  }

  return (
    <div className={styles.date} ref={divRef}>
      <ReactAriaSelect
        aria-label={ariaLabel}
        className={styles.select}
        onSelectionChange={handleOnSelect}
        placeholder={placeholder}
        selectedKey={value as Key}
      >
        <Label className={styles.label}>{label}</Label>
        <Button className={styles.input}>
          <SelectValue />
          <SelectChevron />
        </Button>
        <Popover
          className={styles.popover}
          placement="bottom"
          shouldFlip={false}
          /**
           * react-aria uses portals to render Popover in body
           * unless otherwise specified. We need it to be contained
           * by this component to both access css variables assigned
           * on the container as well as to not overflow it at any time.
           */
          UNSTABLE_portalContainer={divRef.current ?? undefined}
        >
          <ListBox className={styles.listBox}>
            {items.map((item) => (
              <ListBoxItem
                aria-label={String(item)}
                className={styles.listBoxItem}
                id={item}
                key={item}
                textValue={String(item)}
              >
                {item}
              </ListBoxItem>
            ))}
          </ListBox>
        </Popover>
      </ReactAriaSelect>
    </div>
  )
}
