import React from 'react';
import {
    MdFolder, MdImage, MdAudiotrack, MdVideocam, MdAssignment, MdVerticalAlignCenter, MdCropSquare,
    MdEdit, MdSave, MdDone, MdClose,
    MdCheckBox, MdCheckBoxOutlineBlank, MdRadioButtonUnchecked, MdRadioButtonChecked
} from 'react-icons/md';
import {withNamespaces} from 'react-i18next';
import posed from 'react-pose';

import Loading from "../../component/Loading";
import ButtonInteractiveDelete from '../ButtonInteractiveDelete';
import {getCategory, IMAGE, AUDIO, VIDEO, DOCUMENT, ARCHIVE} from '../../lib/FileInfo';
import {injectSheet, withTheme} from '../../lib/theme';
import {InputText} from '../Form';
import StyleGrid from "../../lib/StyleGrid";

const theming = (theme) => ({
    wrapper: {
        display: 'flex',
        transition: '0.25s linear background',
        [StyleGrid.smUp]: {},
        '&:hover': {
            background: theme.bgLight
        },
        '&.list': {
            whiteSpace: 'nowrap',
            margin: (theme.gutter.base / 2) + 'px 0',
            padding: (theme.gutter.base / 2) + 'px ' + theme.gutter.base + 'px',
            width: '100%',
        },
        '&.grid': {
            //margin: theme.gutter.base * 2 + 'px 0',
            padding: theme.gutter.base * 2 + 'px',
        }
    },
    wrapperItem: {
        display: 'flex',
        overflow: 'hidden',
        alignItems: 'center',
        marginRight: 'auto',
        '&.renameOpen': {
            whiteSpace: 'nowrap',
        },
        [StyleGrid.smUp]: {},
    },
    wrapperRename: {
        display: 'flex',
        overflow: 'hidden',
        marginLeft: 'auto',
        flexShrink: 2
    },
    wrapperControls: {
        display: 'flex',
        alignItems: 'center',
        //marginLeft: 'auto',
        '&.list': {},
        '&.grid': {
            padding: theme.gutter.base + 'px',
            marginTop: '-' + (theme.gutter.base * 2) + 'px',
            marginBottom: '-' + (theme.gutter.base * 2) + 'px',
            marginRight: '-' + (theme.gutter.base * 2) + 'px',
        }
    },
    name: {
        '&.list': {
            margin: '0 0 0 ' + theme.gutter.base * 2 + 'px',
        },
        '&.list:not(.renameOpen)': {
            overflowX: 'auto'
        },
        '&.grid': {
            margin: '0 0 0 ' + theme.gutter.base * 2 + 'px',
            wordBreak: 'break-all'
        }
    },
    select: {
        marginRight: theme.gutter.base * 2 + 'px'
    }
});

const WrapperItemButton = posed.button({
    hidden: {
        width: 0,
        marginRight: 0,
        whiteSpace: 'nowrap',
    },
    visible: {
        width: 'auto',
        marginRight: '6px',
    }
});

const WrapperItemDiv = posed.div({
    hidden: {
        width: 0,
        marginRight: 0,
    },
    visible: {
        width: 'auto',
        marginRight: '6px',
    }
});

const Wrapper = withTheme((props) => {
    return (
        'dir' === props.type ?
            <WrapperItemButton className={props.className} style={{color: props.theme.textColor}} onClick={() => props.gotoSubDir(props.name)} withParent={false} pose={props.renameOpen ? 'hidden' : 'visible'}>
                {props.children}
            </WrapperItemButton> :
            <WrapperItemDiv className={props.className} pose={props.renameOpen ? 'hidden' : 'visible'} withParent={false}>
                {props.children}
            </WrapperItemDiv>
    );
});

const ItemIcon = (props) => (
    <React.Fragment>
        {'dir' === props.type ? <MdFolder size={'1.25em'} color={props.color}/> : null}
        {'file' === props.type ?
            IMAGE === props.category ?
                <MdImage size={'1.25em'} color={props.color} style={{flexShrink: 0}}/> :
                AUDIO === props.category ?
                    <MdAudiotrack size={'1.25em'} color={props.color} style={{flexShrink: 0}}/> :
                    VIDEO === props.category ?
                        <MdVideocam size={'1.25em'} color={props.color} style={{flexShrink: 0}}/> :
                        DOCUMENT === props.category ?
                            <MdAssignment size={'1.25em'} color={props.color} style={{flexShrink: 0}}/> :
                            ARCHIVE === props.category ?
                                <MdVerticalAlignCenter size={'1.25em'} color={props.color} style={{flexShrink: 0}}/> :
                                <MdCropSquare size={'1.25em'} color={props.color} style={{flexShrink: 0}}/>
            : null
        }
    </React.Fragment>
);

const WrapperRename = posed.div({
    hidden: {
        width: 0,
        marginRight: 0,
    },
    visible: {
        width: '100%',
        marginRight: '6px',
    }
});

class ContentItem extends React.Component {
    state = {
        renameOpen: false,
        name: '',
    };

    componentDidMount() {
        this.setState({
            name: this.props.item.name
        });
    }

    componentDidUpdate(prevProps) {
        if(prevProps.item.name !== this.props.item.name) {
            this.setState({
                name: this.props.item.name
            });
        }

        if(prevProps.item.renaming !== this.props.item.renaming &&
            'success' === this.props.item.renaming) {
            this.setState({
                renameOpen: false
            });
        }
    }

    handleChange = (event) => {
        this.setState({name: event.target.value});
    };

    keycontrolRename = (e) => {
        e.preventDefault();

        if(e.keyCode === 27) {
            this.setState({
                renameOpen: false,
                name: this.props.item.name
            })
        }

        if(e.keyCode === 13) {
            this.rename();
        }
    };

    rename = () => {
        if(this.props.item && this.props.item.rename) {
            this.props.item.rename(this.state.name);
        }
    };

    select = () => {
        if(this.props.onSelect) {
            this.props.onSelect(this.props.type, this.props.item.name, !this.props.selected);
        }
    };

    render() {
        const {
            theme, classes,
            item, type,
            viewMode,
            gotoSubDir,
            selected, hasSelected, onSelect, multiple
        } = this.props;

        let className = classes.wrapper + ' ' + viewMode;
        const category = getCategory(item.mime);
        if(category) {
            className += ' ' + category;
        }

        const Loader = (props) => {
            return <Loading style={{
                wrapper: {margin: 0},
                item: ('error' === props.doTask ? {borderColor: theme.errorColor} : {}),
            }}/>
        };

        return (
            'finished' === item.deleting ? null :
                <div className={className} style={'grid' === viewMode ? {border: '1px solid ' + theme.textColorLight} : {}}>

                    {onSelect ? (
                        <button className={classes.select} onClick={this.select}>
                            {!multiple ?
                                selected ? <MdRadioButtonChecked size={'1em'} color={theme.textColor}/> : <MdRadioButtonUnchecked size={'1em'} color={theme.textColor}/>
                                : null}
                            {multiple ?
                                selected ? <MdCheckBox size={'1em'} color={theme.textColor}/> : <MdCheckBoxOutlineBlank size={'1em'} color={theme.textColor}/>
                                : null}
                        </button>
                    ) : null}

                    <Wrapper className={classes.wrapperItem + (this.state.renameOpen ? ' renameOpen' : '')}
                             type={type}
                             gotoSubDir={gotoSubDir}
                             name={item.name}
                             renameOpen={this.state.renameOpen && !hasSelected}
                    >
                        <React.Fragment>
                            <ItemIcon type={type} category={category} color={theme.textColor}/>
                            <p className={classes.name + ' ' + viewMode + ' ' + (this.state.renameOpen ? ' renameOpen' : '')}>{item.name}</p>
                        </React.Fragment>
                    </Wrapper>

                    {!hasSelected ?
                        <React.Fragment>
                            <WrapperRename className={classes.wrapperRename} withParent={false} pose={this.state.renameOpen ? 'visible' : 'hidden'}>
                                <InputText onChange={this.handleChange}
                                           onKeyUp={this.keycontrolRename}
                                           value={this.state.name}
                                           style={{width: '100%', margin: 'auto 0', padding: (theme.gutter.base / 2) + 'px ' + theme.gutter.base + 'px'}}
                                />
                            </WrapperRename>

                            <div className={classes.wrapperControls + ' ' + viewMode} style={'grid' === viewMode ? {background: theme.bgLight} : {}}>
                                {this.state.renameOpen ?
                                    <button onClick={this.rename} style={{margin: 'auto ' + theme.gutter.base + 'px'}}><MdSave size={'1.25em'} color={theme.textColor} style={{flexShrink: 0}}/></button>
                                    : null}

                                {('progress' === item.renaming || 'error' === item.renaming ?
                                    <Loader doTask={item.renaming}/> :
                                    'success' === item.renaming ?
                                        <MdDone size={'1.25em'} color={theme.textColor} style={{flexShrink: 0}}/> :
                                        this.state.renameOpen ?
                                            <button onClick={() => this.setState({renameOpen: false, name: item.name})} style={{margin: 'auto ' + theme.gutter.base + 'px'}}>
                                                <MdClose size={'1.25em'} color={theme.textColor} style={{flexShrink: 0}}/>
                                            </button> :
                                            <button onClick={() => this.setState({renameOpen: true})} style={{margin: 'auto ' + theme.gutter.base + 'px'}}>
                                                <MdEdit size={'1.25em'} color={theme.textColor} style={{flexShrink: 0}}/>
                                            </button>)}


                                <ButtonInteractiveDelete size={'1.25em'}
                                                         onClick={item.delete}
                                                         style={{margin: 'auto ' + theme.gutter.base + 'px', flexShrink: 0}}
                                >{('progress' === item.deleting || 'error' === item.deleting ?
                                    <Loader doTask={item.deleting}/> :
                                    null)}</ButtonInteractiveDelete>
                            </div>
                        </React.Fragment>
                        : null}

                </div>
        )
    }
};

export default withNamespaces('file-explorer')(withTheme(injectSheet(theming)(ContentItem)));