import React, { FunctionComponent } from 'react';
import { TreeSelect as AntdTreeSelect } from 'antd';
import { IReactOptionsComponent } from '@wowpic/xform-types';

const renderTreeNode = (options: any, path: string = '') => options.map((option: any) => {
    const title = option.label || option.name;
    return (
        <AntdTreeSelect.TreeNode
            value={option.value}
            title={title}
            key={path ? `${path}-${title}` : title}>
            {option.children
                ? renderTreeNode(option.children, title)
                : null}
        </AntdTreeSelect.TreeNode>
    );
});

const TreeSelect: FunctionComponent<IReactOptionsComponent> = ({
    value,
    options,
    onChange,
    ...props
}) => (
    <AntdTreeSelect
        showSearch
        style={{ width: '100%' }}
        value={value}
        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
        placeholder="Please select"
        allowClear
        treeDefaultExpandAll
        onChange={onChange}
        {...props}>
        {renderTreeNode(options)}
    </AntdTreeSelect>
);

export default TreeSelect;
