/**
 * Component for render options item with dynamically added tooltip
 *
 * @author Brauer Ilya
 * @date 2022-04-25
 */
import * as React from 'react';
import {IOption} from '../select/Select.types';
import {PLACEMENT, POPOVER_THEME} from '../../constants';
import {Tooltip} from '../tooltip/Tooltip';
import * as styles from './optionList.m.scss';

interface IProps {
    option: IOption;
}

interface IState {
    showTooltip: boolean;
}

const tooltipModify = [
    {
        name: 'offset',
        options: {
            offset: [-4, -19]
        }
    }
];

export class OptionItem extends React.Component<IProps, IState> {
    titleRef = React.createRef<HTMLDivElement>();

    override state: IState = {
        showTooltip: false
    };

    override componentDidMount () {
        this.calcTooltip();
    }

    calcTooltip () {
        const titleElement = this.titleRef.current;

        if (titleElement !== null && titleElement.scrollWidth > titleElement.offsetWidth) {
            this.setState({showTooltip: true});
        }
    }

    override render () {
        const option = this.props.option;

        if (this.state.showTooltip === false) {
            return (
                <div ref={this.titleRef}>
                    {option.title}
                </div>
            );
        }

        return (
            <Tooltip
                overlay={(<div className={styles.optionItemOverlay}>{option.title}</div>)}
                placement={PLACEMENT.BOTTOM_START}
                theme={POPOVER_THEME.LIGHT}
                hasArrow={false}
                hasPaddings={false}
                mouseEnterDelay={600}
                modifiers={tooltipModify}
            >
                <div className={styles.optionItem}>{option.title}</div>
            </Tooltip>
        );

    }
}
