import React, { FC, memo, MouseEventHandler, useEffect, useRef } from 'react';
import { Description, Icon }                                     from '../../../';
import { cn }                                                    from '../../util/bem';
import { FormSizesType, SizeType }                               from '../../util/global-props';
import './checkbox.component.scss';

export type CheckboxPropsType = {
    className?: string;
    label?: React.ReactNode;
    disabled?: boolean;
    checked?: boolean;
    defaultChecked?: boolean;

    autoFocus?: boolean;
    height?: FormSizesType;
    margin?: SizeType;
    size?: 'sm' | 'md' | 'lg';
    style?: React.CSSProperties;

    flex?: number;

    onChange?: (checked: boolean) => void;
    onClick?: MouseEventHandler<HTMLInputElement>;
    onMouseUp?: MouseEventHandler<HTMLInputElement>;

    tabIndex?: number;
}

const classNames = cn('checkbox');

export const Checkbox: FC<CheckboxPropsType> = memo((props) => {
    const node = useRef<HTMLInputElement>(null);

    useEffect(() => {
        if (node.current && props.autoFocus && !props.disabled) {
            node.current.focus();
        }
    }, [ props.autoFocus, props.disabled ]);

    const handleClick = () => {
        if (props.disabled || props.defaultChecked) {
            return;
        }
        if (props.onChange) {
            props.onChange(!props.checked);
        }
    };

    const isChecked = props.checked || props.defaultChecked;
    return (
        <div
            className={ classNames({
                checked:  isChecked,
                disabled: props.disabled,
                height:   props.height,
                margin:   props.margin,
                label:    !!props.label,
                size:     props.size
            }, null, props.className) }
            onClick={ handleClick }
            ref={ node }
            style={ props.style }
        >
            <input
                type="checkbox"
                aria-checked={ isChecked }
                tabIndex={ props.tabIndex }
                disabled={ props.disabled }

            />
            <Icon size={ 20 } name={ isChecked ? 'checkboxChecked' : 'checkboxUnchecked' } color="white" style={ props.label ? { marginRight: '11px', pointerEvents: 'none' } : { pointerEvents: 'none' } } />
            { props.label
                ? (
                    <Description size="sm">
                        { props.label }
                    </Description>
                )
                : null }
        </div>
    );
});

Checkbox.defaultProps = {
    defaultChecked: false,
    disabled:       false,
    autoFocus:      false,
    size:           'sm'
};
