import * as React from 'react'
import { connect } from 'react-redux'
import * as cx from 'classnames'
import { StylableComponent } from '../theme'
import {
    FormFieldWrapper,
    WebFormField,
    createEmptyFormField,
    createDefaultFormField,
} from '../form-field'
import { DateTimeInputProps, DateTimeInputComponentProps } from './interfaces'
import { setFormField, FORM_REDUCER_KEY, mapStateToField } from '../form'
import { toUtc, fromUtc, formatDateForInput } from 'ts-datelib'

const styles = require('../../../src/components/form-field/styles.scss')

class Component extends WebFormField<string> {

    public renderField() {
        // console.log('RENDER DATETIME', this.props)

        const { name, formName, disabled, placeholder } = this.props
        return (
            <input
                ref={this.setFieldRef}
                className={this.classNames(styles.datetime)}
                name={name}
                id={`${name}Field`}
                placeholder={placeholder}
                type="datetime-local"
                value={this.parseValueFromState()}
                disabled={disabled}
                onChange={this.onChange}
                onFocus={this.onFocus}
                onBlur={this.onBlur} />
        )
    }
    public getValueFromEvent(e: any) {
        return (this.props as any).saveAsUtc
            ? toUtc(e.currentTarget.value)
            : e.currentTarget.value
    }

    private parseValueFromState = () =>
        formatDateForInput(this.getValueFromState())

}

const initializeInput = (ownProps: DateTimeInputProps): any =>
    createEmptyFormField(
        ownProps.showCurrentDate
            ? (ownProps.value
                ? new Date(ownProps.value).toISOString()
                : new Date().toISOString())
            : '',
        ownProps.required === false ? false : true,
        false,
    )

const mapStateToProps = (state: any, ownProps: DateTimeInputProps) => ({
    ...ownProps,
    field: mapStateToField(state[FORM_REDUCER_KEY], ownProps, initializeInput),
})

const mapDispatchToProps = {
    setFormField,
}

const ConnectedDateTimeInput = connect(mapStateToProps, mapDispatchToProps)(Component)

export class DateTimeInput extends FormFieldWrapper<DateTimeInputProps> {

    public static defaultProps = {
        showCurrentDate: true,
        saveAsUtc: true,
    }

    public render() {
        return (
            <ConnectedDateTimeInput {...this.props} formName={this.formName} />
        )
    }
}
