"use client"

import * as RadixSelect from "@radix-ui/react-select"
import classNames from "classnames"
import React from "react"
import styles from "./select.module.css"

interface RootProps extends RadixSelect.SelectProps {}

export const Root = React.forwardRef<HTMLDivElement, RootProps>(function SelectRoot({ children, ...otherProps }, _ref) {
  return <RadixSelect.Root {...otherProps}>{children}</RadixSelect.Root>
})

export const Trigger = React.forwardRef<HTMLButtonElement, RadixSelect.SelectTriggerProps>(function Trigger(
  { className, children, placeholder, ...otherProps },
  ref,
) {
  return (
    <RadixSelect.Trigger className={classNames(className, styles.trigger)} ref={ref} {...otherProps}>
      {children}
    </RadixSelect.Trigger>
  )
})

export const Value = React.forwardRef<HTMLButtonElement, RadixSelect.SelectValueProps>(function Value(
  {
    children, // NOTE: ignored
    placeholder,
    className,
    ...otherProps
  },
  ref,
) {
  return (
    <span className={classNames(className, styles.value)} {...otherProps} ref={ref}>
      <RadixSelect.Value placeholder={placeholder} />
    </span>
  )
})

interface ContentProps extends RadixSelect.SelectContentProps {
  portalClassName?: string
}

export const Content = React.forwardRef<HTMLDivElement, ContentProps>(function Content(
  { className, children, portalClassName, align = "center", position = "popper", sideOffset = 4, ...otherProps },
  ref,
) {
  return (
    <RadixSelect.Portal className={portalClassName}>
      <RadixSelect.Content
        className={classNames(className, styles.content)}
        ref={ref}
        align={align}
        position={position}
        sideOffset={sideOffset}
        {...otherProps}
      >
        <Select.Viewport>
          <RadixSelect.Group>{children}</RadixSelect.Group>
        </Select.Viewport>
      </RadixSelect.Content>
    </RadixSelect.Portal>
  )
})

export const Viewport = React.forwardRef<HTMLDivElement, RadixSelect.SelectViewportProps>(function Viewport(
  { className, children, ...otherProps },
  ref,
) {
  return (
    <RadixSelect.Viewport className={classNames(className, styles.viewport)} ref={ref} {...otherProps}>
      {children}
    </RadixSelect.Viewport>
  )
})

export const Item = React.forwardRef<HTMLDivElement, RadixSelect.SelectItemProps>(function Item(
  { className, children, value, ...otherProps },
  ref,
) {
  return (
    <RadixSelect.Item className={classNames(className, styles.item)} ref={ref} {...otherProps} value={value}>
      {children}

      <div className={styles.itemText}>
        <RadixSelect.ItemText>{value}</RadixSelect.ItemText>
      </div>
    </RadixSelect.Item>
  )
})

export const Select = {
  Root,
  Trigger,
  Value,
  Content,
  Viewport,
  Item,
}
