// @flow
import React, { useContext, useCallback } from 'react';
import styled from 'styled-components';
import type {
  SegmentedControlItemProps,
  SegmentedControlButtonProps,
} from './segmented-control-item.proptypes';
import { SegmentedControlContext } from '../segmented-control.proptypes';
import { segmentedControlItemPropTypes } from './segmented-control-item.proptypes';
import type { PatchworkComponent } from '../../../../types';
import {
  getLabelFontFamily,
  getLabelFontSize,
  getLabelFontWeight,
  getButtonHoverColor,
  getButtonActiveColor,
  getBackgroundColor,
  getColor,
  getBorderColor,
} from './segmented-control-item.css-rules';
import {
  transitionInstant,
  FOCUS_VISIBLE_SELECTOR,
  getBaseFocusState,
  focusedBoxShadow,
  focusedBorderShadow,
  focusedBorderColor,
} from '../../../../mixins/focus';

const SegmentedControlButton: PatchworkComponent<SegmentedControlButtonProps> = styled.button`
  && {
    background-color: ${getBackgroundColor};
    color: ${getColor};
    font-family: ${getLabelFontFamily};
    font-weight: ${getLabelFontWeight};
    font-size: ${getLabelFontSize};
    padding: 0 15px;
    border: 1px solid ${getBorderColor};
    flex: 1;
    line-height: 40px;
    min-height: 40px;
    ${getBaseFocusState({
      hoverTransition: false,
      activeTransition: false,
      baseTransition: false,
    })}
  }
  ${FOCUS_VISIBLE_SELECTOR} {
    box-shadow: ${focusedBoxShadow},
      ${focusedBorderShadow} ${focusedBorderColor};
  }
  &:first-child {
    border-top-left-radius: 6px;
    border-bottom-left-radius: 6px;
  }
  &:last-child {
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
  }
  &:hover {
    background-color: ${getButtonHoverColor};
    transition: ${transitionInstant};
  }
  &:active {
    background: ${getButtonActiveColor};
    transition: ${transitionInstant};
  }
  &:nth-child(n + 2) {
    border-left: none;
  }
`;

export const SegmentedControlItem = ({
  value,
  children,
}: SegmentedControlItemProps) => {
  const segmentedControlValues = useContext(SegmentedControlContext);
  const clickHandler = segmentedControlValues.onItemClick;
  const itemClickHandler = useCallback(() => clickHandler(value), [
    value,
    clickHandler,
  ]);

  return (
    <SegmentedControlButton
      selected={segmentedControlValues.selectedValue === value}
      onClick={itemClickHandler}
      value={value}
    >
      {children}
    </SegmentedControlButton>
  );
};

SegmentedControlItem.displayName = 'SegmentedControlItem';
SegmentedControlItem.propTypes = segmentedControlItemPropTypes;
