import React from "react";
import style from './CitySelector.module.sass';
import {connect} from "react-redux";
import { reduxForm, Field, change } from 'redux-form';
import {dynamicSearchGetLocation} from "../../../actions/actionCreator";
import ResponseResultContainer from "./CustomSelectorResultSearchContainer/resultSearchContainer";

const CitySelector = (props) => {
    const {input,formName, label, type, meta: { asyncValidating, touched }} = props;
    let { meta: {error} } = props;


    if(input.value == '' || !props.data) {
        error = 'Неверный город!'
    }

    const styleValidationHandler = () => {

        if(touched && error) {
            return style.inputError;
        }else if(touched && !error) {
            return style.inputValid
        }
    };

    const selectValueHandler = (newValue) => {
        props.changeValueForField(
            formName,
            'city',
            newValue['SettlementTypeDescriptionRu'].slice(0, 1)
                + '. ' + newValue['DescriptionRu'] + ', ' + newValue['AreaDescriptionRu']
        );
        props.setQueryForDynamicSearch({
            city: '',
            cityId: newValue.Ref
        });
    };

    const dynamicSearchHandler = (e) => {
        props.setQueryForDynamicSearch({
            city: e.target.value
        });
    };

    return(
        <div>
            <label>{label}</label>
            <div className={asyncValidating ? 'async-validating' : ''}>
                <input
                    {...input}
                    value={input.value}
                    type={type}
                    onKeyUp={dynamicSearchHandler}
                    className={ styleValidationHandler() }
                />
                <ResponseResultContainer
                    selectValueHandler={selectValueHandler}
                />
            </div>
        </div>
    );
};

const mapStateToProps = state => {
    const {settings, data} = state.dynamicSearchLocationReducers;

    return {
        settings, data
    }
};

const mapDispatchToProps = dispatch => ({
    setQueryForDynamicSearch: query => dispatch(dynamicSearchGetLocation(query)),
    changeValueForField: (form, field, value) => dispatch(change(form, field, value))
});


export default connect(mapStateToProps, mapDispatchToProps)(CitySelector);