import React, { useMemo } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Link } from 'lego-on-react';
import block from 'bem-cn';
import isCurrentRoute from 'lib2/isCurrentRoute';

const b = block('nav-link');

function isActive(active, matches, url) {
    if (active !== undefined) {
        return active;
    }

    if (Array.isArray(matches)) {
        return matches.some(match => isCurrentRoute(match));
    }

    if (url !== undefined) {
        return isCurrentRoute(url);
    }
}

function isSameOrigin(url) {
    const origin = new URL(window.location.href).origin;

    return new URL(url, origin).origin === origin;
}

function trySpaClick(url, onClick, history) {
    return event => {
        if (onClick) {
            onClick(event);
        }

        if (url && isSameOrigin(url)) {
            event.preventDefault();
            history.push(url);
        }
    };
}

const NavLink = ({ children, cls, hard, onClick, url, active, matches, ...otherLinkProps }) => {
    let location = useLocation();
    let history = useHistory();

    // eslint-disable-next-line react-hooks/exhaustive-deps
    active = useMemo(() => isActive(active, matches, url), [location]);

    return (
        <Link
            {...otherLinkProps}
            cls={b({ active }).mix(cls)}
            url={url}
            onClick={hard ? onClick : trySpaClick(url, onClick, history)}
        >
            {children}
        </Link>
    );
};

export default NavLink;
