import React, { FunctionComponent, useState, useCallback } from 'react';
import { Transfer as AntdTransfer } from 'antd';
import { IReactOption, IReactTransfer } from '@wowpic/xform-types';

const Transfer: FunctionComponent<IReactTransfer> = ({
    value,
    options = [],
    children,
    onChange,
    ...props
}) => {
    const [selectedKeys, setSelectedKeys] = useState([]);

    const handleSelectChange = useCallback(
        (sourceSelectedKeys, targetSelectedKeys) => {
            setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
        },
        []
    );

    const dataSource = options.map((option: IReactOption) => ({
        ...option,
        key: option.value
    }));

    return (
        <AntdTransfer
            dataSource={dataSource}
            titles={['Source', 'Target']}
            targetKeys={value}
            selectedKeys={selectedKeys}
            onChange={onChange}
            onSelectChange={handleSelectChange}
            render={(item) => item.label}
            {...props}>
            {children}
        </AntdTransfer>
    );
};

export default Transfer;
