import React from 'react';
import { CounterObject, groupBy, Hover, HoverStyle } from '../../helpers';
import SlackCounterGroup from './SlackCounterGroup';

export interface SlackCounterProps {
  counters?: CounterObject[];
  user?: string;
  addButtonStyle?: string;
  onSelect?: (emoji: string) => void;
  onAdd?: () => void;
}

export const SlackCounter: React.VFC<SlackCounterProps> = ({
  counters = defaultProps.counters,
  user = defaultProps.user,
  addButtonStyle = defaultProps.addButtonStyle,
  onSelect = defaultProps.onSelect,
  onAdd = defaultProps.onAdd,
}) => {
  const groups = groupBy(counters, 'emoji');

  return (
    <Hover style={counterStyle}>
      {Object.keys(groups).map(emoji => {
        const names = groups[emoji].map(({ by }: CounterObject) => {
          return by;
        });
        return (
          <div style={groupStyle} key={emoji}>
            <SlackCounterGroup
              emoji={emoji}
              count={names.length}
              names={names}
              active={names.includes(user)}
              onSelect={onSelect}
            />
          </div>
        );
      })}

      <HoverStyle
        hoverStyle={addStyleHover}
        style={addButtonStyle === 'always' ? alwaysStyle : addStyle}
        onClick={onAdd}
      >
        <SlackCounterGroup emoji={''} />
      </HoverStyle>
    </Hover>
  );
};

export const defaultProps: Required<SlackCounterProps> = {
  counters: [
    {
      emoji: '👍',
      by: 'Case Sandberg',
    },
    {
      emoji: '👎',
      by: 'Charlie',
    },
    {
      emoji: '1',
      by: 'Charlie',
    },
    {
      emoji: '2',
      by: 'Charlie',
    },
    {
      emoji: '3',
      by: 'Charlie',
    },
    {
      emoji: '4',
      by: 'Charlie',
    },
    {
      emoji: '5',
      by: 'Charlie',
    },
    {
      emoji: '7',
      by: 'Charlie',
    },
    {
      emoji: '8',
      by: 'Charlie',
    },
    {
      emoji: '9',
      by: 'Charlie',
    },
    {
      emoji: '10',
      by: 'Charlie',
    },
    {
      emoji: '11',
      by: 'Charlie',
    },
    {
      emoji: '12',
      by: 'Charlie',
    },
    {
      emoji: '6',
      by: 'Charlie',
    },
  ],
  user: 'Charlie',
  addButtonStyle: 'hover',
  onSelect: (emoji: string) => {
    console.log(emoji);
  },
  onAdd: () => {
    console.log('add');
  },
};

const counterStyle: React.CSSProperties = {
  display: 'flex',
  flexWrap: 'wrap',
};
const alwaysStyle = {
  cursor: 'pointer',
  fontFamily: 'Slack',
  opacity: '1',
};
const addStyle = {
  cursor: 'pointer',
  fontFamily: 'Slack',
  paddingLeft: '8px',
  opacity: '0',
  transition: 'opacity 0.1s ease-in-out',
};
const groupStyle = {
  marginRight: '4px',
};
const addStyleHover = {
  opacity: '1',
};

export default SlackCounter;
