import React, { useContext, useMemo } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { CardItemHeaderMobile } from 'Components/cardTable/cardItems/cardItemHeader';
import CardTableContext from 'Components/cardTable/cardTableContext';
import { grayColor } from 'Themes/utils/colorPickers';
import { screenSize } from 'Themes/utils/mediaQueries';

export const StyledCardItem = styled.div`
  display: block;
  margin: 0 16px;
  padding: 16px 0;
  flex-basis: 20%;
  border-bottom: 1px solid ${grayColor[0.2]};

  @media ${screenSize('desktop')} {
    border: none;
  }
`;

const useLabel = type => {
  const { sections } = useContext(CardTableContext);

  return useMemo(() => {
    const lobSection = sections.find(section => section.type === type) || {};

    return lobSection.label || '';
  }, [sections, type]);
};

export const BaseCardItem = ({ value, ...props }) => {
  const { type } = props;
  const lobLabel = useLabel(type);

  return (
    <StyledCardItem {...props}>
      <CardItemHeaderMobile theme={props.theme}>
        {lobLabel}
      </CardItemHeaderMobile>
      {value}
    </StyledCardItem>
  );
};

const CardItem = props => {
  const { type } = props;
  let ItemComponent = CardItem.templates[type];

  if (!ItemComponent) {
    ItemComponent = CardItem.templates.default;
  }

  return <ItemComponent {...props} />;
};

CardItem.propTypes = {
  type: PropTypes.string.isRequired,
};

CardItem.displayName = 'CardItem';

CardItem.templates = {
  default: BaseCardItem,
};

CardItem.addTemplates = templates => {
  CardItem.templates = {
    ...CardItem.templates,
    ...templates,
  };
};

export default CardItem;
