import {HTMLProps, VFC} from 'react';

type Option = {
  label: string,
  value: string | number | readonly string[],
  children?: Option[],
}

type DropdownSelectProps = Omit<HTMLProps<HTMLSelectElement>, 'children'> & {
  options?: Option[],
  block?: boolean,
}

const DropdownSelectChildren: VFC<Pick<DropdownSelectProps, 'options'>> = ({
  options,
}) => {
  if (options) {
    return (
      <>
        {options.map(o => {
          if (o.children) {
            return (
              <optgroup
                key={`${o.value}:${o.label}`}
                label={o.label}
              >
                <DropdownSelectChildren
                  options={o.children}
                />
              </optgroup>
            )
          }

          return (
            <option
              key={`${o.value}:${o.label}`}
              value={o.value}
            >
              {o.label}
            </option>
          )
        })}
      </>
    )
  }

  return null
}

export const DropdownSelect: VFC<DropdownSelectProps> = ({
  options,
  block = false,
  style = {},
  ...etcProps
}) => {
  return (
    <select
      {...etcProps}
      style={{
        ...style,
        display: block ? 'block' : style?.display,
        width: block ? '100%' : style?.width,
        height: '2rem',
      }}
    >
      <DropdownSelectChildren
        options={options}
      />
    </select>
  )
}
