import { Chip } from '../../data-display';
import { StyledChipEditor, Input } from '../../inputs/chip-editor/styled-chip-editor';
import { useState } from 'react';
import * as React from 'react';

interface ChipContent {
    title: string;
}

interface Props {
    chips: ChipContent[];
    inputValue: string;
    onChangeInput: (e: { target: { value: string}}) => void;
    id?: string;
    addChip: (chip: string) => void;
    removeChip: (chip: string) => void;
    style?: React.CSSProperties;
}

const ChipEditor = (props: Props) => {
    const handleKeyDown = (e: { charCode: number }) => {
        if (e.charCode === 13) {
            props.addChip(props.inputValue);
            props.onChangeInput({ target: { value: ''}})
        }
    };
    const [myInput, setInput] = useState<any>('');

    const focusInput = () => {
        if((myInput || myInput !== undefined) && myInput.focus){
            myInput.focus();
        }
    };

    return(
        <StyledChipEditor
            onKeyPress={handleKeyDown}
            style={props.style}
            onClick={focusInput}
            id={props.id}
        >
            {props.chips.map(chip => (
                <Chip
                    key={chip.title.toLowerCase()}
                    type='deletable'
                    onClick={() => props.removeChip(chip.title)}
                >
                    {chip.title}
                </Chip>
            ))}
            <Input
                ref={input => { setInput(input); }}
                name='chip-input'
                type='text'
                value={props.inputValue}
                onChange={props.onChangeInput}
            />
        </StyledChipEditor>
    );
};

export default ChipEditor;
