import React from 'react';
import cx from 'classnames';
import { SuiteBadge, renderBadgeIcon } from '../suiteBadge';
import type { SuiteBadgeIconCategory } from '../suiteBadge';
import type { SuiteBadgeProps } from '../suiteBadge/types';
import type { GlyphName16PX } from '@theorchard/suite-icons';

const CLASS_NAME = 'Tag';

type TagVariant = 'flag' | 'category' | 'app';

type TagPropsBase = Omit<SuiteBadgeProps, 'type' | 'icon'> & {
    brand?: string;

    /**
     * Will show a flag icon at left of the text
     *
     * @deprecated Use { variant: 'flag', iconName: 'us'} instead
     */
    flag?: string;

    /**
     * Name of the GlyphIcon to show on variant = 'category'
     */
    iconName?: GlyphName16PX | string;

    /**
     * Defines the type of text and icon to show
     *
     */
    variant?: TagVariant;

    text?: string;

    indicator?: 'warning' | 'error';
};

type TagVariantCond =
    | {
          flag?: never;
          iconName: string;
          variant: 'flag';
      }
    | {
          flag?: never;
          iconName?: GlyphName16PX;
          variant: 'category';
      }
    | {
          flag?: never;
          iconName: string;
          variant: 'app';
      }
    | {
          flag?: string;
          iconName?: never;
          variant?: never;
      };

export type TagProps = TagPropsBase & TagVariantCond;

export const getBadgeIconType = (variant: TagVariant): SuiteBadgeIconCategory => {
    switch (variant) {
        case 'app':
            return 'app';
        case 'category':
            return 'glyph';
        default:
            return 'flag';
    }
};

/**
 * Tags represent a property attached to an object, that is used to characterise it by adding contextual information.
 *
 * @type molecule
 * @status live
 * @tags objects-attributes
 */
export const Tag = ({
    className,
    testId = CLASS_NAME,
    flag,
    iconName,
    variant = 'flag',
    size = 'default',
    ...props
}: TagProps) => {
    const renderIcon = () => {
        // Don't render icons in small variant
        if (size === 'small') return undefined;

        if (flag) return renderBadgeIcon('flag', flag);
        if (!iconName) return;

        const iconType = getBadgeIconType(variant);
        return renderBadgeIcon(iconType, iconName);
    };

    return (
        <SuiteBadge
            {...props}
            className={cx(CLASS_NAME, className, {
                [`${CLASS_NAME}-category`]: variant === 'category',
            })}
            testId={testId}
            type="tag"
            size={size}
            icon={renderIcon()}
        />
    );
};
