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

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

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

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

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

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.TextRich': {
            width: '100%'
        },
        '& .schema-edit--group': {
            margin: '0 auto 3px auto'
        },
        '& > .schema-edit--group p': {
            margin: '0 0 3px 0'
        },
        '& .schema-edit--group-list': {}
    }
});

const SchemaEditor = withNamespaces('page--content-article--meta')(SchemaEditorBase);

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


const initialState = {
    block: {},
    loaded: false,
    hasSchema: false
};

class ContentBlock extends React.Component {

    state = initialState;

    constructor(props) {
        super(props);

        this.saveEvt = new SaveSingle();
    }

    componentWillUnmount() {
        this.setState(initialState);

        this.props.data.rmSave(this.props.root_name, this.props.index);

        if(this.props.rmSave) {
            this.props.rmSave(this.props.data.id);
        }
    }

    //
    // Api Fetch and Push

    fetch(block) {
        this.setState({loaded: 'progress'});
        (new ApiRequest('api', GET, 'content/block/' + block))
            .debug(true)
            .header({})
            .exec()
            .then((res) => {
                if(res && res.data) {
                    this.setState({
                        block: res.data,
                        loaded: true,
                        hasSchema: (!!res.data.schema)
                    });

                    this.props.data.addSave(this.props.root_name, this.props.index, this.saveEvt.trigger);
                } else {
                    this.setState({
                        loaded: 'error'
                    });
                }
            })
            .catch(() => {
                this.setState({
                    loaded: 'error'
                });
            });
    }

    componentDidUpdate(prevProps) {
        if(
            prevProps.data !== this.props.data &&
            this.props.data.id
        ) {
            this.props.data.rmSave(prevProps.root_name, prevProps.index);
            this.fetch(this.props.data.id);
        }
    }

    componentDidMount() {
        if(this.props.data.id) {
            this.fetch(this.props.data.id);

            if(this.props.addSave) {
                this.props.addSave(this.props.data.id, this.saveEvt.trigger);
            }
        }
    }

    render() {
        const {data, t, classes, head, deleteItem, onToggle, open} = this.props;
        const {addSave, rmSave} = this.saveEvt;
        const Hd = head;

        return (
            <React.Fragment>
                <Hd
                    icon={(p) => <MdWidgets size={30} {...p}/>}
                    lbl={t('block.contentBlock') + ' ' + data.id}
                    onToggle={onToggle}
                    deleteItem={deleteItem}
                    showToggle={this.state.hasSchema}
                    open={open}
                />

                <Wrapper className={classes.wrapper} pose={open ? 'visible' : 'hidden'}>

                    {/*<h4 style={{width: '100%'}}>ContentBlock: {data.id}</h4>*/}

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

                    {this.state.block && this.state.block.schema ?
                        <div className={classes.groups}>
                            <SchemaEditor data={this.props.data.data}
                                          schema={this.state.block.schema}
                                          addSave={addSave}
                                          rmSave={rmSave}
                                          cacheid={this.props.uid}
                            />
                        </div> :
                        t('no-editable-meta')
                    }
                </Wrapper>
            </React.Fragment>
        )
    };
}

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