import React, {
    FunctionComponent,
    useState,
    useEffect,
    useCallback
} from 'react';
import { Checkbox as AntdCheckbox } from 'antd';
import { IReactOptionsComponent } from '@wowpic/xform-types';
import { withBatch } from '../utils';

const CheckboxAll: FunctionComponent<IReactOptionsComponent> = ({
    value = [],
    options,
    onChange,
    ...props
}) => {
    const [checkAll, setCheckAll] = useState(value.length === options.length);
    const [indeterminate, setIndeterminate] = useState(
        !!value.length && value.length < options.length
    );

    useEffect(() => {
        setCheckAll(value.length === options.length);
        setIndeterminate(!!value.length && value.length < options.length);
    }, [value]);

    const onCheckedChange = useCallback(
        (aCheckedList) => {
            withBatch(() => {
                onChange(aCheckedList);
                setIndeterminate(
                    !!aCheckedList.length
                    && aCheckedList.length < options.length
                );
                setCheckAll(aCheckedList.length === options.length);
            });
        },
        [options]
    );

    const onCheckAllChange = useCallback(
        (e) => {
            withBatch(() => {
                onChange(
                    e.target.checked ? options.map((item) => item.value) : []
                );
                setIndeterminate(false);
                setCheckAll(e.target.checked);
            });
        },
        [options]
    );

    return (
        <>
            <AntdCheckbox
                className="x-checkbox-all"
                indeterminate={indeterminate}
                onChange={onCheckAllChange}
                checked={checkAll}>
                全选
            </AntdCheckbox>
            <AntdCheckbox.Group
                options={options}
                value={value}
                onChange={onCheckedChange}
                {...props} />
        </>
    );
};

export default CheckboxAll;
