import * as React from 'react'
import { connect } from 'react-redux'
import { StylableComponent } from '../theme'
import { WebFormField, FormFieldWrapper, createAsyncFormField } from '../form-field'
import { FORM_REDUCER_KEY, mapStateToField } from '../form'
import { Location, AddressInputProps } from './interfaces'
import { Spinner } from '../spinner'
import { setFormField } from '../form'
import { searchAddress } from './actions'

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

class _AddressInput extends WebFormField<string> {

    // TODO - implement the async stuff
    // renderSpinner(): JSX.Element {
    //     return <Spinner visible={this.props.field.loading} />
    // }

    public renderField() {
        const { name, formName, disabled, placeholder } = this.props
        // console.log('render text input', this.props)
        return (
            <input
                ref={this.setFieldRef}
                className={this.classNames()}
                name={name}
                id={`${name}Field`}
                placeholder={placeholder}
                type="text"
                value={this.parseAsyncValue()}
                disabled={disabled}
                onChange={this.onChange}
                onFocus={this.onFocus}
                onBlur={this.onBlur} />
        )
    }

    public validate() {
        const { asyncValue } = this.props.field
        if (!asyncValue || !asyncValue.address) {
            return ['* required']
        }
        if (!asyncValue.address.postcode) {
            return ['* valid UK post code required']
        }

        if (!asyncValue.address.town) {
            return ['* valid UK city required']
        }
        return []
    }

    private parseAsyncValue() {
        const { asyncValue } = this.props.field
        // console.log('PARSING ADDRESS VALUE', asyncValue )
        if (asyncValue && asyncValue.address) {
            return [
                Array.isArray(asyncValue.address.streets)
                    ? asyncValue.address.streets.join(', ')
                    : asyncValue.address.streets,
                asyncValue.address.postcode,
            ].join(', ')
        }
        return this.getValueFromState()
    }

}

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

const mapDispatchToProps = {
    setFormField,
    asyncOnChange: searchAddress,
}

const ConnectedAddressInput = connect(mapStateToProps, mapDispatchToProps)(_AddressInput)

export class AddressInput extends FormFieldWrapper<AddressInputProps> {
    public render() {
        return (
            <ConnectedAddressInput {...this.props} formName={this.formName} />
        )
    }
}
