import _ from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import Url from 'lib/Url';
import Metrika from 'lib/metrika';

const Link = React.createClass({

    _handleClick(event) {
        const { onClick, target, to, metrika } = this.props;

        if (metrika) {
            Metrika.send(metrika);
        }

        if (onClick) {
            onClick(event);
        }

        event.preventDefault();

        if (to) {
            Url.open(to, target);
        }
    },

    _onKeyDown(event) {
        if (event.keyCode === 13 && this.props.onClick) {
            this.props.onClick(event);
        }
    },

    render() {
        const linkProps = _.omit(this.props, ['to', 'metrika']);

        if (this.props.to) {
            return (
                <a
                    role="link"
                    tabIndex="0"
                    ref="item"
                    {...linkProps}
                    rel="noopener noreferrer"
                    onClick={this._handleClick}
                    href={this.props.to}
                />
            );
        }

        return (
            <span
                role="link"
                tabIndex="0"
                ref="item"
                {...linkProps}
                onClick={this._handleClick}
                onKeyDown={this._onKeyDown}
            />
        );
    },
});

Link.propTypes = {
    to: PropTypes.string,
    onClick: PropTypes.func,
    className: PropTypes.string,
};

Link.defaultProps = {
    className: 'link link_theme_islands',
};

export default Link;
