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

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

import {ButtonSmall, InputText, Select} from '../../component/Form';
import {withTheme, injectSheet} from '../../lib/theme';
import FormUnique from "../../component/FormUnique";
import ButtonInteractive from "../../component/ButtonInteractive";
import {isAllowedTScope} from "../../lib/i18n";
import {storeGroup} from "./Stores/Group";
import {storeProductType} from "./Stores/ProductTypes";

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

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

const productTypeName = (type, t) => {
    if(isAllowedTScope('shop.product', 'types')) {
        let t_scope = (isAllowedTScope('shop.product', 'types') ? 'defaults.types.' : '');
        return t(t_scope + type, type);
    }

    return t(type);
};

class ProductDetailBaseEdit extends React.Component {

    state = {
        group: '',
        name: '',
        productType: '',
        loadedGroup: false,
        productTypes: [],
        loadedProductTypes: false
    };

    input_name = null;

    constructor(props) {
        super(props);
        this.id = FormUnique();
    }

    componentDidMount() {
        const {
            productInfo,
            loadGroupList,
            loadProductTypeList,
        } = this.props;

        loadGroupList();
        loadProductTypeList();

        this.setState({
            group: productInfo.group,
            name: productInfo.name || '',
            productType: productInfo.product_type || ''
        });

        this.handleDefaultProductType();
    }

    componentDidUpdate(prevProps) {
        if(prevProps.productTypes !== this.props.productTypes){
            this.handleDefaultProductType();
        }
    }

    handleDefaultProductType = () => {
        const {
            productInfo, productTypes, loadingProductTypes
        } = this.props;

        if(true === loadingProductTypes && (!productInfo.product_type || -1 === productTypes.indexOf(productInfo.product_type))) {
            // set first product type received as active when none has set or set has not been found
            this.setState({
                productType: productTypes[0],
            })
        }
    };

    pushBaseData = () => {
        if(this.input_name.checkValidity()) {
            const {pushBaseData, productInfo} = this.props;
            if(productInfo.group === this.state.group) {
                pushBaseData(this.state.name, this.state.productType);
            } else {
                pushBaseData(this.state.name, this.state.productType, this.state.group);
            }
        }
    };

    render() {
        const {
            classes, t, theme,
            saving, open, create,
            groups, loadingGroups,
            productTypes, loadingProductTypes
        } = this.props;

        return (
            <Wrapper className={classes.wrapper} withParent={false} pose={open ? 'visible' : 'hidden'}>
                {(
                    ('progress' === loadingGroups || 'error' === loadingGroups) ||
                    ('progress' === loadingProductTypes || 'error' === loadingProductTypes) ?
                        <Loading style={{
                            wrapper: {margin: 0},
                            item: ('error' === loadingGroups || 'error' === loadingProductTypes ? {borderColor: theme.errorColor} : {}),
                        }}/> :
                        null)}

                {true === loadingGroups && true === loadingProductTypes ?
                    <form onSubmit={(e) => {
                        e.preventDefault();
                        e.target.reportValidity()
                    }}>
                        <div style={{marginBottom: theme.gutter.base * 4 + 'px'}}>
                            <label htmlFor={this.id + '-name'}>{t('edit-base.product-name')}</label>
                            <InputText type='text'
                                       id={this.id + '-name'}

                                       value={this.state.name}
                                       onChange={(e) => this.setState({name: e.target.value})}
                                       ref={(r) => {
                                           this.input_name = r
                                       }}
                                       required
                            />
                        </div>


                        <div style={{marginBottom: theme.gutter.base * 4 + 'px'}}>
                            <label htmlFor={this.id + '-product-type'} style={{marginBottom: theme.gutter.base * 2 + 'px'}}>{t('edit-base.is-product-type')}</label>
                            <Select id={this.id + '-product-type'}
                                    value={this.state.productType}
                                    onChange={(e) => this.setState({productType: e.target.value})}
                            >
                                {0 < productTypes.length ?
                                    productTypes.map((productType, i) => (
                                        <option key={i} value={productType}>{productTypeName(productType, t)}</option>
                                    )) : null
                                }
                            </Select>
                        </div>

                        {!create ?
                            <div style={{marginBottom: theme.gutter.base * 4 + 'px'}}>
                                <label htmlFor={this.id + '-group'} style={{marginBottom: theme.gutter.base * 2 + 'px'}}>{t('edit-base.in-group')}</label>
                                <Select id={this.id + '-group'}
                                        value={this.state.group}
                                        onChange={(e) => this.setState({group: e.target.value})}
                                >
                                    {0 < groups.length ?
                                        groups.map((group, i) => (
                                            <option key={i} value={group.id}>{group.name}</option>
                                        )) : null
                                    }
                                </Select>
                            </div>
                            : null}

                        <ButtonInteractive
                            comp={(p) => (
                                <ButtonSmall {...p}>
                                    {t('btn-' + (create ? 'create' : 'update') + '-product')} {p.children}
                                </ButtonSmall>
                            )}
                            step={create ? false : [
                                null,
                                <MdHelp size={'1em'} color={theme.textColor}/>,
                                <MdDone size={'1em'} color={theme.textColor}/>,
                            ]}
                            onClick={this.pushBaseData}
                        />
                        {('progress' === saving || 'error' === saving ?
                            <Loading style={{
                                wrapper: {margin: 0},
                                item: ('error' === saving ? {borderColor: theme.errorColor} : {}),
                            }}/> :
                            null)}
                    </form> : null}
            </Wrapper>
        )
    };
}

export default withNamespaces('page--shop-product')(withTheme(storeProductType(storeGroup(injectSheet(styling)(ProductDetailBaseEdit)))));