import * as SelectControlBase from '@/base/selectcontrol';
import * as React from 'react';

export interface RenderOptionsProps {
  options: SelectControlBase.SelectOption[],
  optionComponent?: React.ElementType,
  optgroupComponent?: React.ElementType,
  level?: number,
}

export const RenderOptions: React.FC<RenderOptionsProps> = ({
  options,
  optionComponent: Option = 'option',
  optgroupComponent: Optgroup = 'optgroup',
  level = 0,
}: RenderOptionsProps) => (
  options.map((o) => {
    if (typeof o === 'number' || typeof o === 'string') {
      return (
        <Option
          key={`${o}:${o}`}
          value={o}
        />
      );
    }

    if (typeof o.value !== 'undefined') {
      return (
        <Option
          key={`${o.label}:${o.value.toString()}`}
          value={o.value}
          label={o.label}
        >
          {o.label}
        </Option>
      );
    }

    if (typeof o.children !== 'undefined') {
      if (level === 0) {
        return (
          <Optgroup
            key={o.label}
            label={o.label}
          >
            <RenderOptions
              options={o.children}
              optionComponent={Option}
              optgroupComponent={Optgroup}
              level={level + 1}
            />
          </Optgroup>
        );
      }
      return (
        <React.Fragment
          key={o.label}
        >
          <Option
            disabled
          >
            {o.label}
          </Option>
          <RenderOptions
            options={o.children}
            optionComponent={Option}
            optgroupComponent={Optgroup}
            level={level + 1}
          />
        </React.Fragment>
      );
    }

    return null;
  })
);
