import { type ComponentProps, type ReactNode } from 'react'

import { Select as RadixSelect } from 'radix-ui'

import { TbChevronDown } from 'react-icons/tb'

import { contentStyles, triggerStyles, viewportStyles } from './Select.styles'

import { Item } from './Item'

type SelectProps = ComponentProps<typeof RadixSelect.Root> &
	ComponentProps<typeof RadixSelect.Value> &
	ComponentProps<typeof RadixSelect.Content> & {
		trigger?: ReactNode
	}

function Select({
	trigger,
	placeholder,
	children,
	align,
	position = 'popper',
	sideOffset,
	className,
	...props
}: SelectProps) {
	return (
		<RadixSelect.Root {...props}>
			<RadixSelect.Trigger
				asChild={!!trigger}
				className={!trigger ? triggerStyles({ className }) : ''}
			>
				{trigger ? (
					trigger
				) : (
					<>
						<RadixSelect.Value placeholder={placeholder} />
						<RadixSelect.Icon>
							<TbChevronDown />
						</RadixSelect.Icon>
					</>
				)}
			</RadixSelect.Trigger>
			<RadixSelect.Portal>
				<RadixSelect.Content
					align={align}
					position={position}
					sideOffset={sideOffset}
					className={contentStyles({ position, className })}
				>
					<RadixSelect.ScrollUpButton />
					<RadixSelect.Viewport
						className={viewportStyles({ position })}
					>
						{children}
					</RadixSelect.Viewport>
					<RadixSelect.ScrollDownButton />
					<RadixSelect.Arrow />
				</RadixSelect.Content>
			</RadixSelect.Portal>
		</RadixSelect.Root>
	)
}

Select.Item = Item
Select.Value = RadixSelect.Value

export { Select }
