import React, {useEffect} from 'react';
import style from './createGoodsAttributeForm.module.sass';
import { Field, reduxForm, autofill, initialize } from 'redux-form';
import FancyInput from "../../inputs/FansyInput";
import FancyFilePicker from '../../inputs/fancyFilePicker/FancyFilePicker';
import {goodsAttributesTypes} from "../../../constants/goods";
import FancySelector from "../../inputs/fancySelector/fancySelector";
import {
    appendPictureInAttribute,
    deletePictureInGoodsAttributes,
    updateGoodsAttributes
} from "../../../actions/actionCreator";
import {connect} from 'react-redux';
import validate from "../../../utils/validation/goodsAttributesValidate";
import {pathStaticGoodsImages} from "../../../constants/images";





const CreateGoodsAttributeForm = (props) => {
    const {
        valueAttribute,
        nameAttribute,
        price,
        imgUrlArray = [],
        id,
        isNewAttribute = false,
        createGoodsAttributesForm
    } = props;

    const submitHandler = () => {

        const {values, syncErrors} = props.createGoodsAttributesForm;

        if(!syncErrors) {
            props.updateGoodsAttributes(values, props.goodsData.id, id);
        }
        //
        // values = Object.assign(values, {
        //     nameAttribute: goodsAttributesTypes[values.nameAttribute] || 'volume'
        // });
        // props.appendGoodsAttributes(values, id);
    };

    useEffect(() => {
        props.autofill('nameAttribute', nameAttribute || 'volume');
        props.autofill('valueAttribute', valueAttribute);
        props.autofill('price', price);
    }, []);

    const appendFileHandler = (picture) => {
        let formData = new FormData();
        formData.append('file', picture);
        props.appendPicture(formData, id);
    };



    return(
        <form>
            <div className={style.goodsData}>
                <Field
                    name={'nameAttribute'}
                    type={'text'}
                    values={goodsAttributesTypes}
                    isValidation={false}
                    component={FancySelector}
                    isTranslate={true}
                    label={'Тип аттрибута'}
                />
                <Field
                    name={'valueAttribute'}
                    type={'text'}
                    component={FancyInput}
                    label={'Число'}
                />
                <Field
                    name={'price'}
                    type={'text'}
                    component={FancyInput}
                    label={'Стоимость'}
                />
                <div className={style.imageContainer}>
                    {
                        imgUrlArray.map(elem => (
                            <img
                                src={pathStaticGoodsImages + elem}
                                alt={elem}
                                onClick={() => props.deletePicture(id, elem)}
                            />
                        ))
                    }
                    {
                        imgUrlArray.length < 3 && !isNewAttribute && (
                            <Field
                                name={'imgUrlArray'}
                                type={'file'}
                                isValidation={false}
                                onChange={appendFileHandler}
                                maxFiles={3 - imgUrlArray.length}
                                component={FancyFilePicker}
                                label={'Фото для аттрибута'}
                            />
                        )
                    }
                </div>

                <div
                    className={createGoodsAttributesForm && createGoodsAttributesForm.syncErrors
                        ? style.blockedSubmitButton : style.submitButton
                    }
                    onClick={submitHandler}
                >
                    {
                        id ? 'Обновить аттрибут' : 'Добавить аттрибут'
                    }

                </div>
            </div>
        </form>
    );
};

const mapStateToProps = state => {
    const {createGoodsAttributesForm} = state.form;
    const {error} = state.userPersonalDataReducer;
    const {goodsAttributes, newImages, goodsData} = state.createGoodsReducers;

    return {
        error, createGoodsAttributesForm, goodsAttributes, newImages, goodsData
    }
};

const mapDispatchToProps = dispatch => ({
    autofill: (field, value) => dispatch(autofill('createGoodsAttributesForm', field, value)),
    appendPicture: (picture, idAttribute) => dispatch(appendPictureInAttribute(picture, idAttribute)),
    deletePicture: (goodsAttributesId, pictureName) => (
        dispatch(deletePictureInGoodsAttributes(goodsAttributesId, pictureName))
    ),
    updateGoodsAttributes: (goodsAttributesData, idGoods, goodsAttributeId) => (
        dispatch(updateGoodsAttributes(goodsAttributesData, idGoods, goodsAttributeId))
    )
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(reduxForm({
    form: 'createGoodsAttributesForm', // a unique identifier for this form
    initialValues: {nameAttribute: 'volume'},
    enableReinitialize: true,
    validate
})(CreateGoodsAttributeForm))

