import { Icon } from "@ax/components";

import * as S from "./style";

const Tag = (props: ITagProps): JSX.Element => {
	const { type, text, color, icon, textColor, rounded = true, onDeleteAction, className, small, maxChar } = props;

	const truncateText = (str: string, max: number) => {
		if (str.length <= max) return str;
		return `${str.slice(0, max)}...`;
	};

	const displayText = maxChar && text ? truncateText(text, maxChar) : text;

	const handleClick = () => {
		if (onDeleteAction) {
			onDeleteAction();
		}
	};

	const deleteIcon = onDeleteAction ? (
		<S.IconWrapper onClick={handleClick} data-testid="delete-icon-wrapper">
			<Icon name="close" size="16" />
		</S.IconWrapper>
	) : null;

	if (!text) return <></>;

	switch (type) {
		case "status":
			return (
				<S.TagStatus className={className} data-testid="tag-status" title={text || ""}>
					<S.Bullet color={color} />
					{displayText}
				</S.TagStatus>
			);
		case "square":
			return (
				<S.TagSquare color={color} textColor={textColor} className={className} data-testid="tag-square" title={text || ""}>
					{icon && (
						<S.IconTag>
							<Icon name={icon} size="16" />
						</S.IconTag>
					)}
					<div>{displayText}</div>
				</S.TagSquare>
			);
		default:
			return (
				<S.TagFixed color={color} rounded={rounded} small={small} className={className} data-testid="tag-fixed" title={text || ""}>
					<S.TagText>
						<S.Title data-testid="tag-fixed-title">{displayText}</S.Title>
						{deleteIcon}
					</S.TagText>
				</S.TagFixed>
			);
	}
};

export interface ITagProps {
	type?: "status" | "fixed" | "interactive" | "square" | undefined;
	text: string | undefined | null;
	color?: string;
	rounded?: boolean;
	icon?: string;
	textColor?: string;
	onDeleteAction?: () => void;
	className?: string;
	small?: boolean;
	maxChar?: number;
}

export default Tag;
