import React from 'react';
import { NavIcon } from '@theorchard/suite-icons';
import { createHref } from '@theorchard/suite-utils';
import cx from 'classnames';
import { Link, useLocation } from 'react-router-dom';
import { getRoute } from '../../utils';
import { BetaBadge } from './betaBadge';
import { formatTitle } from './utils';
import type { MainNavLinkOptions } from '../../types';

const CLASS_NAME = 'NavLink';

export interface MainNavLinkProps<AppData = unknown>
    extends Omit<MainNavLinkOptions<AppData>, 'Component'> {
    onClick?: React.MouseEventHandler<HTMLAnchorElement>;
    testId?: string;
}

export function MainNavLink<AppData>({
    path,
    match,
    icon,
    navIcon,
    beta,
    term,
    title,
    className,
    routeId,
    testId = CLASS_NAME,
    onClick,
}: MainNavLinkProps<AppData>) {
    const { pathname } = useLocation();
    let linkPath = path;

    if (routeId) {
        linkPath = getRoute(routeId)?.path;

        if (!linkPath)
            throw new Error(
                `Failed to find a route with ID: "${routeId}". Please check the IDs of your routes.`
            );
    }

    if (!linkPath)
        throw new Error(
            'Failed to render main nav link. Please specify a valid "path" or a "routeId" value.'
        );

    return (
        <Link
            to={createHref(linkPath)}
            onClick={onClick}
            data-testid={testId}
            className={cx(CLASS_NAME, className, {
                [`${CLASS_NAME}-selected`]: match?.test(pathname) ?? false,
                withNavIcon: navIcon,
            })}
        >
            {navIcon || icon ? (
                <span className={`${CLASS_NAME}-icon`}>
                    {navIcon ? <NavIcon name={navIcon} /> : icon}
                </span>
            ) : null}

            <span className={`${CLASS_NAME}-title`}>{formatTitle({ term, title })}</span>
            {beta && <BetaBadge className={`${CLASS_NAME}-beta`} />}
        </Link>
    );
}
