import React, { useState } from 'react';
import isString from 'lodash/isString';
import isBoolean from 'lodash/isBoolean';
import Icon from '../Icon/index.jsx';
import { Text } from '../Text/index';
import Card from '../Card/index';
import Shelf from '../Layout/Shelf/index';
import styled from '@emotion/styled';
import { useTheme } from 'emotion-theming';

const textColorMap = intent => {
  if (intent === 'info') return 'Blue';
  if (intent === 'danger') return 'Red';
  return 'Dark Neutral 1';
};

const lineColorMap = intent => {
  if (intent === 'info') return 'Blue';
  if (intent === 'danger') return 'Red';
  if (intent === 'warning') return 'Yellow AA';
  return 'Dark Neutral 1';
};

const getIcon = (icon, intent) => {
  if (isString(icon))
    return <Icon name={icon} color={lineColorMap(intent)} size={16} />

  if (isBoolean(icon) && icon) {
    if (intent === 'info') return <Icon name="warning-circle" color={lineColorMap(intent)} size={16} />
    if (intent === 'danger') return <Icon name="alert-square" color={lineColorMap(intent)} size={16} />
    if (intent === 'warning') return <Icon name="warning-circle" color={lineColorMap(intent)} size={16} />
    return <Icon name="warning-circle" color={lineColorMap(intent)} size={16} />;
  }

  return icon;
}

const StyledClose = styled(Icon)(({ colors, intent }) => ({
  color: colors[lineColorMap(intent)],
  cursor: 'pointer',
  flex: '0 0 16px',
  opacity: 0.4,
  ':hover': {
    opacity: 1,
  }
}))

const Banner = ({
  children,
  onClose,
  intent,
  p = 'xxsmall',
  showCloseButton,
  backgroundColor,
  icon,
  ...cardProps
}) => {
  const theme = useTheme();
  const [visible, setVisible] = useState(true);
  if (!visible) {
    return null;
  }

  return (
    <Card
      display="flex"
      alignItems="center"
      appearance="secondary"
      backgroundColor={backgroundColor}
      intent={intent}
      {...cardProps}
    >
      <Shelf p={p} flexWrap="nowrap" width="100%" justifyContent="space-between">
        <Shelf flexWrap="nowrap" gap="xsmall" alignItems="center">
          {icon && (
            <div style={{ flex: '0 0 16px', display: 'flex' }}>
              {getIcon(icon, intent)}
            </div>
          )}
          <Text color={textColorMap(intent)}>{children}</Text>
        </Shelf>
        {showCloseButton && (
          <StyledClose
            type="button"
            onClick={() => {
              setVisible(false);
              onClose();
            }}
            colors={theme.colors}
            intent={intent}
            size={12}
            name="close"
          />
        )}
      </Shelf>
    </Card>
  );
};

export default Banner;

Banner.defaultProps = {
  intent: 'neutral',
  onClose: () => { },
  showCloseButton: true,
  icon: true,
};
