import React from 'react';
import {
    type AppIcon,
    type BrandIcon,
    GlyphIcon,
} from '@theorchard/suite-icons';
import './link.scss';

/**
 * Defines the available sizes (in pixels) for {@link Link} icons.
 *
 * - `12`: Small
 * - `16`: Medium (default for most use cases)
 */
type LinkIconSize = 12 | 16;

/**
 * Props for the {@link Link} component.
 */
export interface LinkProps {
    /**
     * An optional React element to render as the icon for the link.
     */
    icon?: React.ReactElement<
        typeof AppIcon | typeof BrandIcon | typeof GlyphIcon
    >;
    /**
     * Indicates whether the link is external. Defaults to `false`.
     */
    isExternal?: boolean;
    /**
     * The text label for the link.
     */
    label: string;
    /**
     * Sets / overrides the link's icon size
     */
    size?: LinkIconSize;
    /**
     * The URL the link points to.
     */
    url: string;
}

export const Link: React.FC<LinkProps> = ({
    icon,
    isExternal,
    label,
    size,
    url,
    ...props
}) => {
    const key = `link-${encodeURIComponent(url ?? '')}`;
    size ??= 16;
    return (
        <a
            className="Link"
            data-icon-size={size}
            href={url}
            key={key}
            rel={isExternal ? 'noopener noreferrer' : undefined}
            target={isExternal ? '_blank' : '_self'}
            {...props}
        >
            {icon && icon}
            <span className="Link-label">{label}</span>
            {isExternal && <GlyphIcon name="externalLink" size={size} />}
        </a>
    );
};
