import { Option, Select } from '@citric/core'
import { LoadingCircular } from '@citric/ui'
import { FieldComponent } from '../../form/types'

interface Props {
  isLoading: boolean,
  options: string[],
  renderLabel?: (option: string) => React.ReactNode,
  actions?: { label: string, onSelect: (e: React.ChangeEvent<HTMLSelectElement>) => void }[],
}

export const RawSelectField: FieldComponent<string, Props> = (
  { name, onChange, value, disabled, onBlur, isLoading, options, actions, renderLabel },
) => (
  <div className="select-box">
    <Select
      value={value ?? ''}
      onChange={(e) => {
        const action = actions?.find(a => a.label === e.target.value)
        if (action) {
          action.onSelect(e)
          // e.target.closest('select').value = value 
        }
        else onChange(e.target.value || undefined)
      }}
      name={name}
      disabled={disabled || isLoading}
      aria-busy={isLoading}
      onBlur={onBlur}
    >
      <Option value=""></Option>
      {options.map((o: string) => <Option key={o} value={o}>{renderLabel ? renderLabel(o) : o}</Option>)}
      {actions?.map(({ label }) => <Option key={label} value={label}>{label}</Option>)}
    </Select>
    {isLoading && <div className="loading"><LoadingCircular size="sm" /></div>}
  </div>
)
