/**
 * Component-menu item
 *
 * @author Brauer Ilya
 * @date 2020-04-15
 */

import * as React from 'react';
import {IconName} from '@unidata/icon';
import {Icon, joinClassNames, PLACEMENT, Tooltip} from '../../index';

import * as styles from './menuItem.m.scss';

import * as menuColors from './menuColors';

export type MenuColor = keyof typeof menuColors;

interface IProps {
    icon: IconName;
    title?: string;
    isMinimal?: boolean;
    isActive?: boolean;
    isDisabled?: boolean;
    menuColor?: MenuColor;
    isShow?: boolean;
}

interface IState {
    isShow?: boolean;
    initHide: boolean;
}

const DELAY_TIMEOUT = 150;

export class MenuItem extends React.Component<IProps, IState> {
    override state = {
        isShow: this.props.isShow,
        initHide: false
    };

    override componentDidUpdate (prevProps: Readonly<IProps>, prevState: Readonly<IState>, snapshot?: any): void {
        if (prevState.isShow && !this.state.initHide && !this.props.isShow) {
            this.setState({initHide: true});
            setTimeout(
                () => this.setState({isShow: false}),
                DELAY_TIMEOUT
            );
        } else if (!prevProps.isShow && this.props.isShow) {
            this.setState({isShow: true, initHide: false});
        }
    }

    renderIconWithTooltip = () => {
        const {icon, title} = this.props;

        return (
            <Tooltip overlay={title} placement={PLACEMENT.BOTTOM}>
                <div className={styles.icon}>
                    <Icon name={icon}/>
                </div>
            </Tooltip>
        );
    };

    override render () {
        if (this.state.isShow === false) {
            return null;
        }

        const {icon, title, isMinimal, isActive, isDisabled, menuColor} = this.props;

        const classNameContainer = joinClassNames(
            styles.container,
            [styles.initHide, Boolean(this.state.initHide)],
            [styles.isMinimal, Boolean(isMinimal)],
            [styles.isActive, Boolean(isActive)],
            [styles.isDisabled, Boolean(isDisabled)],
            menuColor !== undefined ? styles[menuColor] : ''
        );

        return (
            <div className={classNameContainer} data-qaid={icon}>
                {isMinimal === true ? this.renderIconWithTooltip() : (
                    <div className={styles.icon}>
                        <Icon name={icon}/>
                    </div>
                )}
                {title !== undefined && isMinimal !== true && (
                    <div className={styles.title}>
                        <span>{title}</span>
                    </div>
                )}
            </div>
        );
    }
}
