import React, { FC, useContext } from 'react';
import { styled } from '../../styles';
import { Context } from './Context';
import * as sc from './styles';
import { Box } from '../Box';
import { Icon } from '../Icon';
import { buttonReset } from '../../styles/utils';
import { ToggleButtonProps } from './definitions';

const ToggleButtonComponent: FC<ToggleButtonProps> = (props, ref) => {
  const {
    checked: checkedProp,
    name: nameProp,
    onChange,
    value,
    children,
    ...other
  } = props;
  const radioGroup = useContext(Context);
  let checked = checkedProp;
  let name = nameProp;

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (other.disabled) return;
    if (onChange) onChange(event);
    if (radioGroup) radioGroup.onChange(event);
  };

  if (radioGroup) {
    if (typeof checked === 'undefined') {
      checked = radioGroup.value === value;
    }
    if (typeof name === 'undefined') {
      name = radioGroup.name;
    }
  }

  return (
    <label>
      <sc.Input
        type={radioGroup ? 'radio' : 'checkbox'}
        name={name}
        checked={checked}
        onChange={handleChange}
        value={value}
        ref={ref}
      />
      <BoxButton {...other} checked={checked}>
        {children}
      </BoxButton>
    </label>
  );
};

const ToggleButton = React.forwardRef(ToggleButtonComponent);

export default ToggleButton;

const BoxButton = styled(Box)<ToggleButtonProps>(
  buttonReset,
  ({ theme, fluid, tight, iconPosition, disabled }) => ({
    whiteSpace: 'nowrap',
    position: 'relative',
    display: 'inline-flex',
    justifyContent: 'center',
    alignItems: 'center',
    flexShrink: 0,
    textAlign: 'center',
    textDecoration: 'none',
    letterSpacing: '0.75px',
    border: 'none',
    padding: '0.75rem 1.75rem',
    minHeight: '2.5rem',
    minWidth: tight ? '100px' : '128px',
    lineHeight: theme.lineHeights.tight,
    fontFamily: theme.fontFamilies.baseText,
    fontSize: theme.fontSizes[1],
    fontWeight: theme.fontWeights.semiBold,
    borderRadius: '8px',
    ...(fluid && { width: '100%' }),

    ...(disabled && {
      backgroundColor: theme.colors.disabled,
      color: theme.colors.inactive,
      boxShadow: 'none',
      cursor: 'not-allowed',
    }),

    [Icon]: {
      ...(iconPosition && {
        [`margin${sc.getIconStyle(iconPosition)}`]: theme.space.s,
      }),
    },
  }),
  sc.getVariant
);
