import cx from 'classnames';
import { bool, node, string } from 'prop-types';
import React, { useRef, forwardRef, useLayoutEffect } from 'react';
import Icon from '../Icon';
import style from './Checkbox.module.scss';
import { useTheme } from 'emotion-theming';

const Checkbox = forwardRef(
  (
    { children, checked, textColor = 'Dark Neutral 1', className, indeterminate, ...rest },
    userRef,
  ) => {
    const defaultRef = useRef();
    const theme = useTheme();
    const ref = userRef || defaultRef;

    useLayoutEffect(() => {
      ref.current.indeterminate = indeterminate;
    }, [ref, indeterminate]);

    return (
      <label className={cx(style.label, className)}>
        <input type="checkbox" checked={checked} className={style.input} ref={ref} {...rest} />
        <span className={style.shape}>
          {checked && !indeterminate && (
            <Icon className={style.checkedIcon} name="tick" size={12} />
          )}
        </span>
        {children && (
          <span className={style.text} style={{ color: theme.colors[textColor] || textColor }}>
            {children}
          </span>
        )}
      </label>
    );
  },
);

Checkbox.propTypes = {
  textColor: string,
  children: node,
  checked: bool,
  indeterminate: bool,
  className: string,
};

export default Checkbox;
