import * as React from 'react'
import * as cx from 'classnames'

import { IconProps, IconPropsKey } from '../interfaces'

const styles = require('../../src/styles/components/icon.scss')

const rotations = [90, 180, 270]

interface ContainerStyles {
    width?: string
    height?: string
}

interface IconStyles {
    fill?: string
    stroke?: string
}

export class Icon extends React.Component<IconProps, {}> {
    public static defaultProps: Partial<IconProps> = {
        size: 18,
    }

    public render(): JSX.Element {
        const { id, onClick } = this.props

        return (
            <svg
                id={id}
                className={this.containerClassName()}
                style={this.containerStyles()}
                onClick={onClick}>
                <use
                    className={this.iconClassName()}
                    xlinkHref={this.xLinkHref()}
                    style={this.iconStyles()} />
            </svg>
        )
    }

    private containerClassName(): string {
        const { className, containerClassName, rotate } = this.props

        return cx(
            styles.container,
            {
                [styles[`rotate${rotate}`]]: rotate !== undefined,
            },
            containerClassName,
            className,
        )
    }

    private containerStyles(): ContainerStyles {
        const { size } = this.props
        const containerStyles: ContainerStyles = {}

        const sizeStyles = {
            width: `${size}px`,
            height: `${size}px`,
        }

        return {
            ...containerStyles,
            ...sizeStyles,
        }
    }

    private iconClassName(): string {
        const { className, stroke, fill } = this.props
        return cx(
            className,
            {
                [styles['primary-stroke']]: stroke === 'primary',
                [styles['primary-fill']]: fill === 'primary',
            },
        )
    }

    private iconStyles(): IconStyles {
        const { primary, stroke, fill } = this.props
        const iconStyles: IconStyles = {}

        const strokeStyles = !primary && stroke ? { stroke } : {}
        const fillStyles = !primary && fill ? { fill } : {}

        return {
            ...iconStyles,
            ...strokeStyles,
            ...fillStyles,
        }
    }

    private xLinkHref(): string {
        const { href, icon } = this.props
        return href || `#icon-${icon}`
    }
}
