// @flow
import React, { useCallback } from 'react';
import styled from 'styled-components';
import type {
  ClickableListProps,
  ClickableListItemProp,
} from './clickable-list.proptypes';
import { Box } from '../../../primitives';
import { UnstyledButton } from '../../behaviors';
import { ChevronRight } from '../../icon';
import { FieldLabel, Span } from '../../typography';
import { FormList } from '../form-list';
import { getPaletteColor } from '../../../mixins/branding';

const StyledFieldLabel = styled(FieldLabel)`
  && {
    padding-bottom: 14px;
  }
`;

const ListItemButton = styled(UnstyledButton)`
  && {
    width: 100%;
    outline: none;
    min-height: inherit;
    opacity: 1;
    transition: opacity 300ms ease;
  }

  &:active,
  &:disabled {
    opacity: 0.5;
  }
`;

const ClickableListItemIcon = styled.span`
  height: 35px;
  margin: 0 20px 0 0;
  text-align: center;
  width: 35px;
  border-radius: 50%;
  background-color: ${props => getPaletteColor(props.backgroundColor)};
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;

  img {
    border-radius: 50%;
    max-width: 100%;
  }
`;

const ListItem = ({
  onClick,
  id,
  disabled,
  text,
  icon,
}: ClickableListItemProp & { onClick: (id: string) => void }) => {
  const handleClick = useCallback(() => {
    onClick(id);
  }, [id, onClick]);

  return (
    <ListItemButton
      insetFocus
      type="submit"
      onClick={handleClick}
      disabled={disabled}
    >
      <Box
        spacing={['pr1', 'pl3']}
        stacked="row"
        align="center"
        justify="space-between"
      >
        {icon ? (
          <Box align="center" stacked="row" justify="space-between">
            <ClickableListItemIcon backgroundColor={icon.backgroundColor}>
              {typeof icon.imgSrc === 'string' ? (
                <img src={icon.imgSrc} alt={icon.altText} />
              ) : (
                icon.imgSrc
              )}
            </ClickableListItemIcon>
            <Span fontSize="f2" fontFace="sans" bold>
              {text}
            </Span>
          </Box>
        ) : (
          <Span fontSize="f2" fontFace="sans" bold>
            {text}
          </Span>
        )}

        <ChevronRight justify="end" />
      </Box>
    </ListItemButton>
  );
};

export const ClickableList = ({
  label,
  options,
  onClick,
  disabled,
}: ClickableListProps) => (
  <Box>
    <StyledFieldLabel>{label}</StyledFieldLabel>
    <FormList
      items={options.map(option => (
        <ListItem
          id={option.id}
          key={option.id}
          text={option.text}
          onClick={onClick}
          disabled={disabled || option.disabled}
          icon={option.icon}
        />
      ))}
    />
  </Box>
);

ClickableList.displayName = 'ClickableList';
