import { remcalc, rndId } from '../../shared/functions';
import { colors } from '../../shared/constants';
import { baseBox, Baseline } from '../../shared/composers';
import styled, { css } from 'styled-components';
import React from 'react';

const StyledText = styled.span`
  padding: 1rem;
  display: inline-block;
`;

const StyledDiv = styled.div`
  display: inline-block;
  background-color: ${colors.base.grey};

  ${baseBox()}
`;

const inputStyled = css`
  background-size: 200% 100%;
  transition:all .5s ease;
  min-width: ${remcalc(120)};
  text-align: center;
`;


const StyledInput0 = styled.input`
  display: none;

  & + span {
    background: linear-gradient(to right,
                transparent 50%,
                ${colors.base.white} 50%);
    background-position: left bottom;
    box-shadow: inset
                ${remcalc(-7)} 0 ${remcalc(9)} ${remcalc(-7)}
                rgba(0,0,0,0.4);

    ${inputStyled}
  }

  &:checked {
    & + span {
      background-position: right bottom;
    }
  }
`;

const StyledInput1 = styled.input`
  display: none;

  & + span {
    background: linear-gradient(to right,
                ${colors.base.white} 50%,
                transparent 50%);
    background-position: right bottom;

    ${inputStyled}
  }

  &:checked {
    & + span {
      background-position: left bottom;
    }
  }
`;

/*
TODO: Remove !important - it is used to overirde a global style
 */
const StyledLabel = styled.label`
  margin-bottom: 0 !important;
`;

const Toggle = ({
  options = [{
    label: 'On',
    checked: true
  }, {
    label: 'Off',
    checked: false
  }],
  ...props
}) => {
  const _options = options.map( (option, index) => {
    if (index >= 2) {
      return null;
    }

    const customProps = {
      defaultChecked: option.checked,
      name: 'toggler',
      type: 'radio',
      value: option.label,
      id: rndId()
    };

    const InputVarients = {
      input_0: (
        <StyledInput0 {...customProps} />
      ),
      input_1: (
        <StyledInput1 {...customProps} />
      )
    };

    return (
      <StyledLabel
        htmlFor={customProps.id}
        key={index}
      >
        {InputVarients[`input_${index}`]}
        <StyledText>{option.label}</StyledText>
      </StyledLabel>
    );
  });

  return (
    <StyledDiv {...props}>
      {_options}
    </StyledDiv>
  );
};

Toggle.propTypes = {
  options: React.PropTypes.array
};

export default Baseline(
  Toggle
);
