import React from 'react';
import {withNamespaces} from 'react-i18next';
import {Redirect} from 'react-router-dom';

import {withTheme, injectSheet} from '../../lib/theme';
import {i18n} from "../../lib/i18n";

import ProductDetailBaseEdit from './ProductDetailBaseEdit';
import {storeProduct} from "./Stores/Product";
import {cancelPromise} from "../../component/cancelPromise";

const styling = theme => ({
    wrapper: {
        overflow: 'hidden'
    },
});

class ProductCreate extends React.Component {
    state = {
        saving: false,
        newProduct: false,
    };


    pushNewProduct = (name, product_type) => {
        const {createProduct, cancelPromise} = this.props;

        this.setState({saving: 'progress'});
        cancelPromise(createProduct(this.props.group, name, product_type))
            .then((data) => {
                if(data.error) {
                    this.setState({saving: 'error'});
                    return;
                }

                this.setState({
                    saving: 'success',
                    newProduct: data.success
                });

                setTimeout(() => {
                    this.setState({
                        newProduct: false
                    });
                }, 0);

                setTimeout(() => {
                    this.setState({saving: false});
                }, 4000);
            })
            .catch((data) => {
                if(!data.cancelled) {
                    this.setState({saving: 'error'});
                }
            });
    };

    render() {
        const {
            group
        } = this.props;

        return (
            <React.Fragment>
                {
                    (
                        this.state.newProduct
                    ) ? <Redirect to={'/' + i18n.languages[0] + '/shop/products/' + this.props.group + '/' + this.state.newProduct}/>
                        : null
                }
                <ProductDetailBaseEdit pushBaseData={this.pushNewProduct}
                                    productInfo={{group: group}}
                                    open={true}
                                    saving={this.state.saving}
                                    create={true}
                />
            </React.Fragment>
        )
    };
}

export default withNamespaces('page--shop-product')(cancelPromise(storeProduct(withTheme(injectSheet(styling)(ProductCreate)))));