import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { modifierCSS } from '../../../helpers';

const propTypes = {
  /**
   * The content of the FormCheck label.
   */
  children: PropTypes.node,

  /**
   * The className property allows you to add more classes to the component.
   */
  className: PropTypes.string,

  /**
   * The color of the FormCheck, mainly used for validation state.
   */
  color: PropTypes.oneOf(['', 'success', 'warning', 'danger']),

  /**
   * The component default class.
   */
  defaultClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),

  /**
   * You can use the isIndeterminate prop to style the FormCheck so the user knows that the state
   * is indeterminate.
   */
  isIndeterminate: PropTypes.bool,

  /**
   * You can use the isInline prop so the FormCheck will be displayed inline.
   */
  isInline: PropTypes.bool,

  /**
   * You can use the isRadio prop, so the type of the input check is radio.
   */
  isRadio: PropTypes.bool,

  /**
   * The component used for the root node.
   * Either a string to use a DOM element or a component.
   */
  tag: PropTypes.elementType,

  /**
   * Customize the aspect of the FormCheck by using the variant prop.
   * Available options are button, button-light and toggle.
   */
  variant: PropTypes.oneOf(['', 'button', 'button-light', 'button-denim-300', 'toggle']),

  /**
   * You can use this to pass prop to the label for example label
   */
  labelProps: PropTypes.object,
};

const defaultProps = {
  children: '',
  className: '',
  color: '',
  defaultClassName: 'sui-a-form-check',
  isIndeterminate: false,
  isInline: false,
  isRadio: false,
  tag: 'label',
  variant: '',
  labelProps: {},
};

export const FormCheck = React.forwardRef(({
  children,
  className,
  color,
  defaultClassName,
  isIndeterminate,
  isInline,
  isRadio,
  tag: Tag,
  variant,
  labelProps,
  ...attributes
}, ref) => {
  const inputef = useRef(null);
  useEffect(() => {
    if (inputef.current) {
      inputef.current.indeterminate = isIndeterminate;
    }
  }, [isIndeterminate]);

  const classes = classnames(
    className,
    defaultClassName,
    isInline ? 'as--inline' : '',
    modifierCSS(color),
    modifierCSS(variant),
  );
  const { name } = attributes;

  return (
    <Tag className={classes} ref={ref} data-testid={`label-${name}`}>
      <input type={isRadio ? 'radio' : 'checkbox'} ref={inputef} {...attributes} />
      <span className="sui-a-form-check__indicator" />
      <label className="sui-a-form-check__label" {...labelProps}>
        {children}
      </label>
    </Tag>
  );
});

FormCheck.propTypes = propTypes;
FormCheck.defaultProps = defaultProps;
