// @flow
import React from 'react';
import styled from 'styled-components';
import randomstring from 'randomstring';
import type { RadioButtonProps } from './radio-button.proptypes';
import { radioButtonPropTypes } from './radio-button.proptypes';
import { getFontFamily, getFontSize } from '../../../mixins/typography';
import { getPaletteColor } from '../../../mixins/branding';

import { Box } from '../../../primitives';
import { RadioOption } from '../../icon/radio-option';
import {
  getBaseFocusState,
  focusedBoxShadow,
  focusedBorderShadow,
  focusedBorderColor,
  focusedBorderRadius,
} from '../../../mixins/focus';

const RadioButtonContainer = styled(Box)`
  cursor: pointer;
  position: relative;
  ${getBaseFocusState({ hoverTransition: false, activeTransition: false })}
  &:focus-within {
    box-shadow: ${focusedBoxShadow},
      ${focusedBorderShadow} ${focusedBorderColor};
  }
  border-radius: ${focusedBorderRadius};
`;

const StyledRadioOption = styled(RadioOption)`
  margin-left: -${({ theme }) => theme.spacing.s1};
`;

const Label = styled.label`
  color: ${getPaletteColor('greyscale-black')};
  cursor: pointer;
  font-size: ${getFontSize};
  font-family: ${getFontFamily};
  display: flex;
  align-items: center;
  /* stylelint-disable property-no-vendor-prefix  */
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE, Edge */
  /* stylelint-enable */
  user-select: none; /* Chrome, Opera */
  margin-top: 9px;
  margin-bottom: 11px;
  z-index: -1;
`;

const InvisibleInput = styled.input`
  height: 0;
  width: 0;
  margin: 0;
  padding: 0;
  opacity: 0;
`;

const Wrapper = styled.div`
  transform: scale(1);
`;

export const RadioButton = ({
  id,
  text,
  selected,
  onClick,
  name,
}: RadioButtonProps) => {
  const onClickWithEvent = _e => onClick(id);
  const randomIdentifier = `${randomstring.generate({
    length: 5,
    charset: 'alphabetic',
  })}-${id}`;
  const label =
    text != null ? (
      <Label face="sans" fontSize="f1" htmlFor={randomIdentifier}>
        {text}
      </Label>
    ) : null;

  return (
    <Wrapper>
      <RadioButtonContainer
        stacked="row"
        align="center"
        onClick={onClickWithEvent}
      >
        <InvisibleInput
          id={randomIdentifier}
          readOnly
          type="radio"
          checked={selected}
          name={name}
        />
        <StyledRadioOption checked={selected} />
        {label}
      </RadioButtonContainer>
    </Wrapper>
  );
};

RadioButton.displayName = 'RadioButton';
RadioButton.propTypes = radioButtonPropTypes;
