import React from 'react';
import {withNamespaces} from 'react-i18next';

import Loading from "../../component/Loading";

import SchemaEditor from "../../component/Schema/EditorLoader";

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

import {storeSchema} from "../Content/Stores/Schema";

const styling = theme => ({
    wrapper: {
        overflow: 'hidden',
    },
    groups: {
        display: 'flex',
        flexWrap: 'wrap',
        //margin: '0 -3px',
        /*'& > .schema-edit--group': {
            width: '100%',
            padding: '0 3px',
            marginBottom: '3px',
        },

        '& .schema-edit--group': {
            margin: '0 auto 3px auto'
        },
        '& > .schema-edit--group .schema-edit--lbl': {
            margin: '0 0 ' + theme.gutter.base + 'px 0'
        },
        '& .schema-edit--group-list': {}*/
    }
});

class ProductDetailLocaleData extends React.PureComponent {

    fetch(schema, force = false) {
        const {loadSchema} = this.props;
        loadSchema(schema, force);
    }

    componentDidUpdate(prevProps) {
        if(prevProps.schema !== this.props.schema) {
            this.fetch(this.props.schema);
        }
    }

    componentDidMount() {
        if(this.props.schema) {
            this.fetch(this.props.schema);
        }
    }

    render() {
        const {
            t, classes,
            schema, cacheid, addSave, rmSave,
            data,
            isSchemaLoaded, schemas
        } = this.props;

        return (
            <div className={classes.wrapper}>

                <h3 style={{width: '100%'}}>{t('editdata.title')}</h3>

                {('progress' === isSchemaLoaded(schema) || 'error' === isSchemaLoaded(schema) ?
                    <Loading
                        style={{
                            wrapper: {margin: 0},
                        }}
                        errorWarning={'error' === isSchemaLoaded(schema)}
                    /> :
                    null)}

                {true === isSchemaLoaded(schema) ?
                    <React.Fragment>
                        <SchemaEditor data={data || {}}
                                      schema={schemas[schema]}
                                      addSave={addSave}
                                      rmSave={rmSave}
                                      cacheid={cacheid}
                                      displayBlock={true}
                                      tScope={'product.' + this.props.schema}
                        />
                    </React.Fragment> :
                    (!this.props.schema ? <p>{t('view-error.schema-not-set')}</p> :
                        ((false !== isSchemaLoaded(schema) && 'progress' !== isSchemaLoaded(schema)) ? <p>{t('view-error.schema-not-loaded')}</p> : null))
                }
            </div>
        )
    };
}

export default withNamespaces('page--shop-product')(storeSchema(withTheme(injectSheet(styling)(ProductDetailLocaleData))));