// Lib
import React, {Component} from 'react';
import posed from 'react-pose';

import {InputText} from '../../Form';

import ButtonInteractiveDelete from '../../ButtonInteractiveDelete';

import {withTheme, injectSheet} from '../../../lib/theme';

const styling = theme => ({
    wrapper: {
        display: 'flex',
        overflow: 'hidden',
        height: 0,
        paddingBottom: 0,
    },
    item: {
        margin: '0 3px 0 0',
    },
    toggle: {
        display: 'flex',
        alignItems: 'center',
        flexDirection: 'row'
    }
});

const Wrapper = posed.div({
    hidden: {
        height: 0,
        paddingBottom: 0,
    },
    visible: {
        height: 'auto',
        paddingBottom: '3px',
    }
});

class StringListItem extends Component {

    state = {
        open: false
    };

    constructor(props) {
        super(props);
        this.refInp = React.createRef();
    }

    componentWillUnmount() {
        if(this.props.rmSave) {
            this.props.rmSave(this.props.uid);
        }
    }

    componentDidMount() {
        setTimeout(() => {
            this.setState({open: true});
        }, 1000);

        if(this.props.addSave) {
            this.props.addSave(this.props.uid, () => {
                return this.refInp.current.value;
            });
        }
    }

    delete = (key) => {
        if(this.props.deleteItem) {
            this.setState({open: false});
            this.props.deleteItem(key);
        }

        // todo: refac when true-deletion is implemented
        if(this.props.rmSave) {
            this.props.rmSave(this.props.uid);
        }
    };

    render() {
        const {classes} = this.props;

        return (
            <Wrapper className={classes.wrapper} pose={this.state.open ? 'visible' : 'hidden'}>
                <InputText
                    className={classes.item}
                    data-name={this.props.name + '-' + this.props.uid}
                    type='text'
                    defaultValue={this.props.val}
                    ref={this.refInp}
                />

                <ButtonInteractiveDelete onClick={this.delete}/>
            </Wrapper>
        );
    }
}

export default withTheme(injectSheet(styling)(StringListItem));