import * as React from 'react';

import {iconData, IconIntent} from '@unidata/icon';

import {createHtmlPropsFilter} from '../../utils/createHtmlPropsFilter';
import {getSizeThemeKey} from '../../utils/getSizeThemeKey';
import {getIntentThemeKey} from '../../utils/getIntentThemeKey';
import {joinClassNames} from '../../utils/joinClassNames';

import {SIZE, TRIGGER} from '../../constants';

import {Props} from './Icon.types';

import * as theme from './icon.m.scss';
import {Tooltip} from '../tooltip/Tooltip';

const filterProps = createHtmlPropsFilter<Props, React.SVGAttributes<SVGElement>>([
    'name',
    'size',
    'intent',
    'title'
]);

export class Icon extends React.Component<Props, any> {
    override render () {
        const props = this.props;
        const {name, size = SIZE.MIDDLE, intent = IconIntent.DEFAULT} = props;
        const sizeThemeKey = getSizeThemeKey<keyof typeof theme>('icon', size);
        const intentThemeKey = getIntentThemeKey<keyof typeof theme>('icon', intent);
        const className = joinClassNames(theme.icon, theme[sizeThemeKey], theme[intentThemeKey]);
        const iconSvgProps = iconData[name] ? iconData[name].svg : {};

        const svgProps: React.SVGProps<SVGSVGElement> = {
            ...iconSvgProps,
            ...filterProps(props),
            className,
            dangerouslySetInnerHTML: iconData[name] && iconData[name].content ?
                {__html: iconData[name].content} : undefined
        };

        if (props.title) {
            return (
                <Tooltip
                    overlay={props.title}
                    trigger={props.titleTrigger || TRIGGER.HOVER_TARGET_ONLY}
                >
                    <svg {...svgProps} />
                </Tooltip>
            );
        }

        return <svg {...svgProps} />;
    }
}
