import React, { useState, useCallback, memo } from 'react';
import PropTypes from 'prop-types';
import styled, { css } from 'styled-components';
import { textSize } from 'Themes/utils/fontPickers';
import { secondaryColor, grayColor } from 'Themes/utils/colorPickers';

const selectedColors = css`
  color: ${secondaryColor};
  border-bottom-color: ${secondaryColor};
`;

const tabColors = ({ selected }) =>
  selected
    ? selectedColors
    : css`
        color: inherit;
        border-bottom-color: transparent;
      `;

const StyledTabs = styled.div`
  background: none;
  border-bottom: 1px solid ${grayColor[0.4]};
`;

const Tab = styled.button`
  font-size: ${textSize('S')};
  background: none;
  border: 2px solid transparent;
  padding: 0 0 16px 0;
  margin-right: 25px;
  cursor: pointer;
  ${tabColors}

  :focus {
    outline: 0;
  }

  :hover {
    ${selectedColors}
  }
`;

const Tabs = ({
  options,
  selectedOption: initSelectedOption,
  onSelect,
  ...props
}) => {
  const [selectedOption, setSelectedOption] = useState(initSelectedOption);

  const TabWithSelected = useCallback(
    option => {
      const onClick = useCallback(() => {
        onSelect(option);
        setSelectedOption(option);
      }, [option, onSelect]);

      return (
        <Tab
          key={`tab-option-${option}`}
          selected={option === selectedOption}
          onClick={onClick}
        >
          {option}
        </Tab>
      );
    },
    [options, selectedOption, onSelect],
  );

  return <StyledTabs {...props}>{options.map(TabWithSelected)}</StyledTabs>;
};

Tabs.propTypes = {
  selectedOption: PropTypes.string,
  options: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
  onSelect: PropTypes.func.isRequired,
};

Tabs.displayName = 'Tabs';

export default Tabs;
