import React from 'react';
import {withNamespaces} from "react-i18next";
import posed from 'react-pose';
import {MdInfo, MdSave} from "react-icons/md";

import Loading from '../../component/Loading';

import {withTheme, injectSheet} from '../../lib/theme';
import {Select} from "../../component/Form";

const theming = (theme) => ({
    wrapper: {
        display: 'table',
        tableLayout: 'fixed',
        border: 0,
        width: '100%'
    },
    item: {
        display: 'table-row'
    },
    cell: {
        display: 'table-cell',
        padding: theme.gutter.base * 2 + 'px',
        '&:first-child': {
            paddingLeft: 0
        },
        '&:last-child': {
            paddingRight: 0
        }
    },
    itemDetail: {},
    itemDetailCell: {
        overflow: 'hidden'
    },
    detailTop: {
        display: 'flex',
    },
    detailCustomer: {
        display: 'flex',
        flexDirection: 'column',
        '& p': {
            margin: '0 0 ' + theme.gutter.base + 'px 0'
        }
    },
    detailShipping: {
        display: 'flex',
    },
    detailProducts: {},
    detailProductsItem: {
        display: 'flex'
    },
    detailProductsItemQty: {
        fontWeight: 'bold',
        margin: '0 ' + theme.gutter.base * 2 + 'px 0 0'
    },
    detailProductsItemDetail: {
        '& p': {
            margin: '0 0 ' + theme.gutter.base * 2 + 'px 0'
        }
    },
    detailStateLog: {},
    detailStateLogTransition: {
        textAlign: 'center',
        margin: theme.gutter.base + 'px 0',
        padding: theme.gutter.base * 2 + 'px 0',
    },
    detailStateLogTransitionTime: {
        margin: '0 0 ' + theme.gutter.base + 'px 0',
    },
    detailStateLogTransitionTrans: {
        margin: 0
    }
});


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

class OrdersListItem extends React.Component {

    state = {
        selectedState: 'none',
        showDetails: false
    };

    componentDidUpdate(prevProps) {
        if(prevProps.item !== this.props.item) {
            this.setState({
                selectedState: this.props.item.state || 'none',
                showDetails: false
            });
        }
    }

    componentDidMount() {
        this.setState({
            selectedState: this.props.item.state || 'none'
        });
    }

    onChange = (evt) => {
        if(evt.target.value !== this.state.selectedState) {
            this.setState({selectedState: evt.target.value});
        }
    };

    render() {
        const {
            t, theme, classes,
            index, item,
            pushStateUpdate, savingStateUpdate
        } = this.props;

        return (
            <React.Fragment>
                <tr className={classes.item}>
                    <td className={classes.cell}>
                        {item.date}
                    </td>
                    <td className={classes.cell}>
                        {item.customer && (item.customer.name || item.customer.email) ?
                            item.customer.name ?
                                item.customer.name :
                                item.customer.email :
                            t('list.item.customer-no-data')
                        }
                    </td>
                    <td className={classes.cell}>
                        {item.products ? item.products.length : 0}
                    </td>
                    <td className={classes.cell}>
                        <Select value={this.state.selectedState} onChange={this.onChange} style={{maxWidth: '125px'}}>
                            <option value='none'>{t('list.state.none')}</option>
                            <option value='open'>{t('list.state.open')}</option>
                            <option value='payment-pending'>{t('list.state.payment-pending')}</option>
                            <option value='shipped'>{t('list.state.shipped')}</option>
                            <option value='delivered'>{t('list.state.delivered')}</option>
                            <option value='returned'>{t('list.state.returned')}</option>
                            <option value='finished'>{t('list.state.finished')}</option>
                        </Select>
                        {'none' !== this.state.selectedState && this.state.selectedState !== this.props.item.state ?
                            <button onClick={() => {
                                pushStateUpdate(index, item.id, this.state.selectedState);
                            }}><MdSave color={theme.textColor}/></button> : null
                        }
                        {('progress' === savingStateUpdate[item.id] || 'error' === savingStateUpdate[item.id] ?
                            <Loading style={{
                                wrapper: {margin: 0},
                                item: ('error' === savingStateUpdate[item.id] ? {borderColor: theme.errorColor} : {}),
                            }}/> :
                            null)}
                    </td>
                    <td className={classes.cell}>
                        {item.shipping ? item.shipping : t('list.item.shipping-none')}
                    </td>
                    <td className={classes.cell}>
                        {item.locale}
                    </td>
                    <td className={classes.cell} style={{width: '1.5em'}}>
                        <button onClick={() => this.setState({showDetails: !this.state.showDetails})}><MdInfo size={'1.25em'} color={theme.textColor}/></button>
                    </td>
                </tr>
                <tr className={classes.itemDetailCell}>
                    <td colSpan={7}>
                        <ItemDetail className={classes.itemDetailCell} withParent={false} pose={this.state.showDetails ? 'visible' : 'hidden'}>
                            <div className={classes.detailTop}>
                                <div className={classes.detailCustomer}>
                                    <p style={{fontWeight: 'bold'}}>{t('list.item.detail.customer.title')}</p>
                                    {item.customer ?
                                        <React.Fragment>
                                            <p>{t('list.item.detail.customer.name')} {item.customer.name ? item.customer.name : t('list.item.detail.customer.not-set')}</p>
                                            <p>{t('list.item.detail.customer.email')} {item.customer.email ? item.customer.email : t('list.item.detail.customer.not-set')}</p>
                                            <p>{t('list.item.detail.customer.street')} {item.customer.street ? item.customer.street : t('list.item.detail.customer.not-set')}</p>
                                            <p>{t('list.item.detail.customer.street_no')} {item.customer.street_no ? item.customer.street_no : t('list.item.detail.customer.not-set')}</p>
                                            <p>{t('list.item.detail.customer.post_code')} {item.customer.post_code ? item.customer.post_code : t('list.item.detail.customer.not-set')}</p>
                                            <p>{t('list.item.detail.customer.city')} {item.customer.city ? item.customer.city : t('list.item.detail.customer.not-set')}</p>
                                            <p>{t('list.item.detail.customer.country')} {item.customer.country ? item.customer.country : t('list.item.detail.customer.not-set')}</p>
                                        </React.Fragment> :
                                        <p>{t('list.item.detail.customer.none')}</p>}
                                </div>
                                <div className={classes.detailShipping}>
                                </div>
                            </div>
                            <div className={classes.detailProducts}>
                                <p style={{fontWeight: 'bold'}}>{t('list.item.detail.product.title')}</p>
                                {item.products.map((product, i) => (
                                    <div className={classes.detailProductsItem} key={i}>
                                        <p className={classes.detailProductsItemQty}>{product.qty ? product.qty : 0}x</p>
                                        <div className={classes.detailProductsItemDetail}>
                                            {product.product.data && product.product.data.info ?
                                                <p>{t('list.item.detail.product.name')} {product.product.data.info.name}</p> :
                                                <p>{t('list.item.detail.product.no-info')}</p>
                                            }
                                            <p>{t('list.item.detail.product.product_no')} {product.product.product_no ? product.product.product_no : <em>{t('list.item.detail.product.product_no-missing')}</em>}</p>
                                            <p><small>{t('list.item.detail.product.id')} {product.product.id}</small></p>
                                        </div>
                                    </div>
                                ))}
                            </div>
                            <div className={classes.detailStateLog}>
                                <p style={{fontWeight: 'bold'}}>{t('list.item.detail.state-log.title')}</p>
                                {item.state_log ?
                                    // todo: find way to display reverse (problem: reverse() reverses on every statechange)
                                    item.state_log.map((transition, i) => (
                                        <div className={classes.detailStateLogTransition} key={i} style={{border: '1px solid ' + theme.textColorLight}}>
                                            <p className={classes.detailStateLogTransitionTime}>{new Date(transition.time * 1000).toLocaleString()}</p>
                                            <p className={classes.detailStateLogTransitionTrans}>{transition.from} > <span style={{
                                                textDecoration: (item.state_log.length - 1) === i ? 'underline' : 'none'
                                            }}>{transition.to}</span></p>
                                        </div>
                                    )) :
                                    <p>{t('list.item.detail.state-log.none')}</p>
                                }
                            </div>
                        </ItemDetail>
                    </td>
                </tr>
            </React.Fragment>
        )
    };
}

export default withNamespaces('page--shop-order')(withTheme(injectSheet(theming)(OrdersListItem)));