import React, { useRef, useState } from 'react';
import { GroupWrap } from './style';
import Checkbox from './';
import { ICheckboxGroup } from './types';

const Group = function({ options = [], onChange, values = [], defaultValues = [], ...rest }: ICheckboxGroup) {
    const [checked, setCheck] = useState<any>(defaultValues);
    const defaultSetted = useRef(false);

    if (checked.join() !== values.join() && !defaultSetted.current) {
        setCheck(values);
    }
    if (defaultValues.length && !defaultSetted.current) {
        defaultSetted.current = true;
        setCheck([...defaultValues]);
    }
    return (
        <GroupWrap {...rest}>
            {options.map((o, index) => (
                <Checkbox
                    key={index}
                    checked={checked.includes(o.value)}
                    disabled={o.disabled}
                    onChange={isChecked => {
                        if (isChecked && !checked.includes(o.value)) {
                            checked.push(o.value);
                        } else if (!isChecked && checked.includes(o.value)) {
                            checked.splice(checked.findIndex((i: any) => i === o.value), 1);
                        }
                        onChange && onChange([...checked].sort());
                    }}
                >
                    {o.label}
                </Checkbox>
            ))}
        </GroupWrap>
    );
};
export default Group;
