"use client"
import { useEffect, useRef, useState, type FocusEvent } from "react"

import {
  Button,
  Label,
  ListBox,
  ListBoxItem,
  Popover,
  Select as ReactAriaSelect,
  SelectValue,
  type Key,
} from "react-aria-components"
import SelectChevron from "../../SelectChevron"

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

import type { SelectProps } from "./select"

export default function Select({
  items,
  label,
  name,
  onSelect,
  placeholder,
  value,
}: SelectProps) {
  const divRef = useRef<HTMLDivElement>(null)
  const [divElement, setDivElement] = useState(divRef.current)

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

  useEffect(() => {
    if (divRef.current) {
      setDivElement(divRef.current)
    }
  }, [divRef.current])

  return (
    <div className={styles.date} ref={divRef}>
      <ReactAriaSelect
        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={divElement ?? undefined}
        >
          <ListBox aria-label={name} 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>
  )
}
