"use client"

import * as React from "react"
import { cn } from "../core/cn"
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
  SelectGroup,
  SelectGroupLabel,
} from "./select"

export interface SimpleSelectOption {
  value: string
  label: string
  disabled?: boolean
}

export interface SimpleSelectGroup {
  group: string
  items: SimpleSelectOption[]
}

export type SimpleSelectOptions = SimpleSelectOption[] | SimpleSelectGroup[]

interface SimpleSelectProps {
  value: string
  onValueChange: (value: string) => void
  options: SimpleSelectOptions
  placeholder?: string
  disabled?: boolean
  size?: 'sm' | 'default'
  className?: string
}

function isGrouped(options: SimpleSelectOptions): options is SimpleSelectGroup[] {
  return options.length > 0 && 'group' in options[0]
}

function SimpleSelect({
  value,
  onValueChange,
  options,
  placeholder = "Select...",
  disabled = false,
  size = 'default',
  className,
}: SimpleSelectProps) {
  return (
    <Select value={value} onValueChange={onValueChange} disabled={disabled}>
      <SelectTrigger
        className={cn(
          size === 'sm' && 'h-7 text-xs px-2',
          className
        )}
      >
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {isGrouped(options)
          ? options.map(g => (
              <SelectGroup key={g.group}>
                <SelectGroupLabel>{g.group}</SelectGroupLabel>
                {g.items.map(item => (
                  <SelectItem key={item.value} value={item.value} disabled={item.disabled}>
                    {item.label}
                  </SelectItem>
                ))}
              </SelectGroup>
            ))
          : (options as SimpleSelectOption[]).map(item => (
              <SelectItem key={item.value} value={item.value} disabled={item.disabled}>
                {item.label}
              </SelectItem>
            ))
        }
      </SelectContent>
    </Select>
  )
}

export { SimpleSelect }
