import { createListCollection, Field, Select, type SelectRootProps } from '@chakra-ui/react'
import { ChevronDown } from 'lucide-react'
import { useMemo, type ReactNode } from 'react'

export interface SelectOption {
  label: string
  value: string
}

export interface CalledItSelectProps extends Omit<SelectRootProps, 'collection'> {
  options: SelectOption[]
  placeholder?: string
  label?: ReactNode
  errorText?: ReactNode
}

export function CalledItSelect({
  options,
  placeholder = 'Select...',
  label,
  errorText,
  ...props
}: CalledItSelectProps) {
  const collection = useMemo(
    () => createListCollection({ items: options }),
    [options],
  )

  return (
    <Field.Root invalid={Boolean(errorText)}>
      {label && <Field.Label color="heading">{label}</Field.Label>}
      <Select.Root collection={collection} {...props}>
        <Select.HiddenSelect />
        <Select.Trigger borderColor={errorText ? 'red.400' : 'border'} bg="panel" minW="180px">
          <Select.ValueText placeholder={placeholder} />
          <Select.Indicator>
            <ChevronDown size={16} />
          </Select.Indicator>
        </Select.Trigger>
        <Select.Positioner>
          <Select.Content>
            {options.map((option) => (
              <Select.Item key={option.value} item={option}>
                <Select.ItemText>{option.label}</Select.ItemText>
                <Select.ItemIndicator />
              </Select.Item>
            ))}
          </Select.Content>
        </Select.Positioner>
      </Select.Root>
      {errorText && <Field.ErrorText>{errorText}</Field.ErrorText>}
    </Field.Root>
  )
}
