import { Select, SelectItem, SelectSkeleton, TextInput } from "carbon-components-react";
import { useField, FastField } from "formik";
import React, { useState, useEffect } from "react";

interface Props {
    name: string;
    label?: string;
    options?: any[];
    keyValue?: string;
    displayvalue?: string;
    isLoading?: boolean;
}

export default function GlobitsSelectInput(props: Props) {
    const { label, name, options, keyValue, displayvalue, isLoading } = props;
    const [field, meta] = useField(props.name);

    const [value, setValue] = useState(field.value);

    useEffect(() => {
        setValue(field.value);
    }, [field.value]);

    const onChange = (event: any) => {
        setValue(event.target.value);
        field.onChange(event);
    }

    return (
        <>
            {isLoading ? (
                <SelectSkeleton />
            ) : (
                <Select
                    id={name}
                    defaultValue="placeholder-item"
                    labelText={label}
                    onChange={onChange}
                    value={value}
                // helperText="Optional helper text"
                >
                    <SelectItem
                        disabled
                        hidden
                        value="placeholder-item"
                        text="Choose an option"
                    />
                    {options.map((item, pos) => {
                        return (
                            <SelectItem
                                key={pos} value={item[keyValue ? keyValue : "value"]}
                                text={item[displayvalue ? displayvalue : "name"]}
                            />
                        );
                    })}
                </Select>
            )}
        </>

    );
}
