import React, { ReactNode } from "react";
import classNames from "classnames";
import { Box, BoxProps } from "../Box";
import { bem } from "../../utilities/bem";
import { STATUS_VARIANT } from "../../types";
import { Flex } from "../Flex";
import { Icon, ICON_TYPE } from "../Icon";
import { Text } from "../Text";

const cn = "StatusLabel";

export enum STATUS_LABEL_ICON_POSITION {
  LEFT = "left",
  RIGHT = "right",
}

export interface StatusLabelProps extends BoxProps {
  icon?: ICON_TYPE;
  iconPosition?: STATUS_LABEL_ICON_POSITION;
  iconFontSize?: string;
  variant?: STATUS_VARIANT;
  colorLabel?: boolean;
  removeIcon?: boolean;
}

type StatusIconProps = {
  icon: ICON_TYPE;
  iconPosition: STATUS_LABEL_ICON_POSITION;
  iconFontSize: string;
  variant: STATUS_VARIANT;
};

type StatusTextProps = {
  children: ReactNode;
  variant: STATUS_VARIANT;
  colorLabel?: boolean;
};

const StatusIcon = ({
  icon,
  iconPosition,
  iconFontSize,
  variant,
}: StatusIconProps) => (
  <Icon
    style={{ fontSize: iconFontSize }}
    className={classNames(
      bem(cn, { e: "icon" }),
      bem(cn, { e: "icon", m: variant }),
      { right: "ml-1", left: "mr-1" }[
        iconPosition === STATUS_LABEL_ICON_POSITION.RIGHT ? "right" : "left"
      ],
    )}
    icon={icon}
  />
);

const StatusText = ({ children, variant, colorLabel }: StatusTextProps) => (
  <Text
    className={classNames(
      bem(cn, { e: "label" }),
      colorLabel && bem(cn, { e: "label", m: variant }),
    )}
  >
    {children}
  </Text>
);

export const StatusLabel = (props: StatusLabelProps) => {
  const {
    icon = ICON_TYPE.CIRCLE,
    iconPosition = STATUS_LABEL_ICON_POSITION.LEFT,
    iconFontSize = "60%",
    variant = STATUS_VARIANT.DEFAULT,
    colorLabel,
    removeIcon,
    className,
    children,
    ...rest
  } = props;

  const iconProps = {
    icon,
    iconPosition,
    iconFontSize,
    variant,
  };

  if (removeIcon) {
    return (
      <Box className={classNames(bem(cn), className)} {...rest}>
        <StatusText colorLabel={colorLabel} variant={variant}>
          {children}
        </StatusText>
      </Box>
    );
  }

  return (
    <Flex className={classNames(bem(cn), className)} {...rest}>
      {iconPosition === STATUS_LABEL_ICON_POSITION.LEFT && (
        <StatusIcon {...iconProps} />
      )}
      <StatusText colorLabel={colorLabel} variant={variant}>
        {children}
      </StatusText>
      {iconPosition === STATUS_LABEL_ICON_POSITION.RIGHT && (
        <StatusIcon {...iconProps} />
      )}
    </Flex>
  );
};
