/** @format */

import * as React from 'react';
import {Checkbox, Row, Col} from 'antd';
import styles from '../../list/styles/accountList.module.scss';
const CheckboxGroup = Checkbox.Group;

interface CheckboxProps {
    rowOptions: any;
    value?: number[];
    isDisabled?: boolean;
    onChange?: (val: number[]) => {};
}

export default React.forwardRef((props: CheckboxProps, ref) => {
    const {rowOptions, value, onChange, isDisabled} = props;
    const [state, setState] = React.useState({
        checkedList: value,
        indeterminate: true,
        checkAll: false,
    });
    let groupOption = rowOptions.children.map((ele: {name: string; id: number}) => {
        return {
            label: ele.name,
            value: ele.id,
        };
    });
    React.useEffect(() => {
        let checkStatus = [];
        if (value && rowOptions.children) {
            checkStatus = rowOptions.children.filter((item: {id: number}) => value.includes(item.id));
        }
        setState(prevState => ({
            ...prevState,
            checkedList: value,
            indeterminate: !!checkStatus.length && checkStatus.length < rowOptions.children.length,
            checkAll: checkStatus.length == rowOptions.children.length,
        }));
    }, [value]);

    const itemChange = (checkedList: number[]) => {
        setState(prevState => ({
            ...prevState,
            indeterminate: !!checkedList.length && checkedList.length < groupOption.length,
            checkAll: checkedList.length === groupOption.length,
            checkedList: checkedList,
        }));
        onChange(checkedList);
    };
    const onCheckAllChange = (e: any) => {
        const newRow = groupOption.map((ele: {value: number}) => {
            return ele.value;
        });
        setState(prevState => ({
            ...prevState,
            checkAll: e.target.checked,
            checkedList: e.target.checked ? newRow : [],
            indeterminate: false,
        }));
        onChange(e.target.checked ? newRow : []);
    };
    return (
        <Row key={rowOptions.id} className={styles.checkRow}>
            <Col span={24} className={styles.checkGroup_heck}>
                <Checkbox
                    indeterminate={state.indeterminate}
                    disabled={isDisabled}
                    checked={state.checkAll}
                    onChange={onCheckAllChange}
                >
                    <span>{rowOptions.name}</span>
                </Checkbox>
            </Col>
            <Col style={{marginLeft: 10}}>
                <CheckboxGroup
                    options={groupOption}
                    disabled={isDisabled}
                    value={state.checkedList}
                    onChange={itemChange}
                />
            </Col>
        </Row>
    );
});
