import React from 'react';
import {View,TouchableOpacity,Text} from 'react-native';
import Icon from './Icon';
import DateTimePicker from 'react-native-modal-datetime-picker';
import DateHelper from "./DateUtil";
import PropTypes from "prop-types";

class DateTimeInput extends React.Component {

    renderDate(){
        if(!(this.props.value instanceof Date)) return ' - ';
        switch (this.props.mode) {
            case 'datetime':
                return <Text>{DateHelper.formatDateTime(this.props.value)}</Text>;
            case 'date':
                return <Text>{DateHelper.formatDate(this.props.value)}</Text>;
            case 'time':
                return <Text>{DateHelper.formatTime(this.props.value)}</Text>
        }
    }

    constructor(props){
        super(props);
        this.state = {
            visibility: false
        }
    }

    render(){
        return(
            <View style={{flexDirection: 'row', paddingVertical: 10}}>
                <Text style={[{fontWeight: 'bold'}, this.props.error === '' ? undefined: styles.errorText]}>{this.props.label} </Text>
                <TouchableOpacity style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between'}}
                                  onPress={() => this.setState({visibility: true})}>
                    <View style={{flex: 1}}>
                        {this.renderDate()}
                    </View>
                    <Icon name={'calendar'} class={'SimpleLineIcons'} size={25} color={this.props.error === '' ? undefined: 'red'}/>
                </TouchableOpacity>
                <DateTimePicker
                    mode={this.props.mode}
                    isVisible={this.state.visibility}
                    onConfirm={(value) => {
                        this.props.onSelect(value);
                        this.setState({visibility: false});
                    }}
                    onCancel={() => this.setState({visibility: false})}
                />
            </View>
        )
    }
}

DateTimeInput.propTypes = {
    isVisible: PropTypes.bool,
    error: PropTypes.string,
    value: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    onSelect: PropTypes.func.isRequired,
    mode: PropTypes.string
};

DateTimeInput.defaultProps = {
    isVisible: false,
    mode: 'datetime',
    error: ''
};

export default DateTimeInput;