import React, { ReactElement } from 'react';
import css from '../../utils/css';
import Icon from '../Icon';

import {
  StyledTag,
  CloseButton,
  Intent,
  Variant,
  ThemeVariant,
} from './StyledTag';

import { CommonProps } from '../common';

export interface TagProps extends CommonProps {
  /**
   * Visual intent color to apply to tag. It is required for `filled` and `outlined` variants.
   */
  intent?: 'primary' | 'success' | 'danger' | 'warning' | 'error' | 'archived';
  /**
   * Click handler for remove button, receiving tag's text and value.
   */
  onRemove?: (tag: {
    text: string | ReactElement;
    value?: string | number;
  }) => void;
  /**
   * Tag size.
   */
  size?: 'small' | 'medium' | 'large';
  /**
   * Tag label.
   */
  text: string | ReactElement;
  /**
   * Tag's uniq value. Use this when you wish to use removable tag to accientally remove tag with same text.
   */
  value?: string | number;
  /**
   * Tag type.
   */
  variant?: 'basic' | 'filled' | 'outlined';
}
const FILLED_VARIANTS = {
  primary: 'filled-primary',
  success: 'filled-success',
  danger: 'filled-danger',
  warning: 'filled-warning',
  error: 'filled-error',
  archived: 'filled-archived',
} as const;

const OUTLINED_VARIANTS = {
  primary: 'outlined-primary',
  success: 'outlined-success',
  danger: 'outlined-danger',
  warning: 'outlined-warning',
  error: 'outlined-error',
  archived: 'outlined-archived',
} as const;

const getThemeVariant = (variant: Variant, intent: Intent): ThemeVariant => {
  switch (variant) {
    case 'basic':
      return variant;
    case 'filled':
      return FILLED_VARIANTS[intent];
    case 'outlined':
      return OUTLINED_VARIANTS[intent];
  }
};

const Tag = ({
  value,
  text,
  variant = 'basic',
  intent = 'primary',
  size = 'medium',
  onRemove,
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: TagProps): ReactElement => {
  const themeVariant = getThemeVariant(variant, intent);

  return (
    <StyledTag
      themeVariant={themeVariant}
      themeSize={size}
      id={id}
      className={className}
      style={{ ...style, ...css(sx) }}
      data-test-id={dataTestId}
    >
      {text}
      {onRemove !== undefined && (
        <CloseButton
          type="button"
          themeVariant={themeVariant}
          onClick={(e): void => {
            e.preventDefault();
            onRemove({ text, value });
          }}
        >
          <Icon icon="cancel" />
        </CloseButton>
      )}
    </StyledTag>
  );
};

export default Tag;
