import * as React from 'react';

import { array, bool, number, oneOf, oneOfType, string } from 'prop-types';

import { Box } from '../Layout';
import css from '@styled-system/css';
import { get } from '@styled-system/css';
import styled from '@emotion/styled';
import { useTheme } from 'emotion-theming';
import Token from '../Token';

const Styled = styled(Box)(
  css({
    borderRadius: 'card',
    maxWidth: '100%',
  }),
  ({ scrollable }) =>
    scrollable && {
      maxHeight: 315,
      overflowY: 'auto',
    },
  ({
    width,
    appearance,
    colors,
    backgroundColor,
    borderColor,
    borderWidth,
    borderRadius,
    hasToken,
  }) =>
    css({
      position: hasToken && 'relative',
      width: width === 'medium' ? 240 : 'auto',
      borderRadius: borderRadius || 'card',
      boxShadow: appearance === 'default' ? 'card' : undefined,
      border: appearance === 'default' ? undefined : `${borderWidth || '1px'} solid`,
      borderWidth,
      borderColor: borderColor || colors.borderColor,
      backgroundColor: backgroundColor || colors.backgroundColor,
    }),
);

const Card = ({
  width = 'auto',
  scrollable,
  appearance = 'default',
  backgroundColor,
  borderColor,
  borderWidth,
  borderRadius,
  intent = 'neutral',
  p = 'xsmall',
  tokenText,
  tokenColor = 'Orange',
  tokenFontColor = 'White',
  children,
  ...rest
}) => {
  const theme = useTheme();
  const config = get(theme, 'components.Card', {});
  const colors = get(config, `intents.${intent}`, {});

  return (
    <Styled
      p={p}
      width={width}
      scrollable={scrollable}
      appearance={appearance}
      borderColor={borderColor}
      borderRadius={borderRadius}
      borderWidth={borderWidth}
      backgroundColor={backgroundColor}
      intent={intent}
      colors={colors}
      hasToken={!!tokenText}
      {...rest}
    >
      {tokenText && (
        <Token
          style={{ position: 'absolute', top: '-23px', left: '10px' }}
          fontSize="12px"
          backgroundColor={tokenColor}
          color={tokenFontColor}
          size="small"
        >
          {tokenText}
        </Token>
      )}
      {children}
    </Styled>
  );
};

Card.propTypes = {
  p: oneOfType([string, number, array]),
  width: oneOf(['auto', 'medium', 'max']),
  appearance: oneOf(['default', 'secondary']),
  intent: oneOf(['neutral', 'warning', 'info', 'danger']),
  scrollable: bool,
};

export default Card;
