import React from 'react';
import {withNamespaces} from 'react-i18next';
import posed from 'react-pose';
import {MdDone} from 'react-icons/md';

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

import {ButtonSmall as Button} from '../../component/Form';
import SchemaEditor from "../../component/Schema/EditorLoader";

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

import {SaveSingle} from '../../component/ContentStore';

import apiSchema from './ApiSchema';

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

        '& .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': {}
    }*/
});

const initialState = {
    schema: false,
    loaded: false
};

const Wrapper = posed.div({
    hidden: {
        height: 0,
        marginTop: 0,
    },
    visible: {
        height: 'auto',
        marginTop: '24px',
    }
});

class ArticleDetailMeta extends React.PureComponent {

    state = initialState;

    constructor(props) {
        super(props);

        this.saveEvt = new SaveSingle();
    }

    componentWillUnmount() {
        this.setState(initialState);
    }

    //
    // Api Fetch and Push

    fetch(schema) {
        this.setState({loaded: 'progress'});
        apiSchema.onGet(schema, (state) => {
                this.setState({
                    loaded: state
                });
            },
            (data) => {
                if(data) {
                    this.setState({
                        schema: data,
                        loaded: true
                    });
                } else {
                    this.setState({
                        loaded: 'error'
                    });
                }
            }
        );
    }

    trigger = () => {
        if(!this.props.saveFn) {
            console.error('ArticleMeta: can not save, no prop `saveFn` binding exits.');
            return;
        }

        this.props.saveFn(this.saveEvt.trigger());
    };

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

    componentDidMount() {
        if(this.props.meta._schema) {
            this.fetch(this.props.meta._schema);
        }
    }

    render() {
        const {t, classes, open, cacheid, saving, theme} = this.props;
        const {addSave, rmSave} = this.saveEvt;

        return (
            <Wrapper className={classes.wrapper} withParent={false} pose={(open ? 'visible' : 'hidden')}>

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

                {('progress' === this.state.loaded || 'error' === this.state.loaded ?
                    <Loading
                        style={{
                            wrapper: {margin: 0},
                        }}
                        errorWarning={'error' === this.state.loaded}
                    /> :
                    null)}

                {this.props.meta && this.state.schema ?
                    <React.Fragment>
                        <SchemaEditor data={this.props.meta}
                                      schema={this.state.schema}
                                      tScope={'article-meta'}
                                      addSave={addSave}
                                      rmSave={rmSave}
                                      cacheid={cacheid}
                        />

                        <Button onClick={this.trigger}>{t('editmeta.save')}</Button>

                        {saving ?
                            ('progress' === saving || 'error' === saving ?
                                <React.Fragment>
                                    <Loading style={{
                                        wrapper: {margin: 0},
                                        item: ('error' === saving ? {borderColor: theme.errorColor} : {}),
                                    }}/>

                                </React.Fragment> :
                                ('success' === saving ?
                                    <MdDone/> : null))
                            : null}
                    </React.Fragment> :
                    (!this.props.meta._schema || (false !== this.state.loaded && 'progress' !== this.state.loaded)) ? <p>{t('view-error.no-editable-meta')}</p> : null
                }
            </Wrapper>
        )
    };
}

export default withNamespaces('page--content-article')(withTheme(injectSheet(styling)(ArticleDetailMeta)));