'use client';

import { bool } from 'prop-types';
import { CheckboxProps } from './checkbox.types';
import { RippleArea } from '../../ripple/ripple-area';
import useRippleEffect from '../../ripple/hooks/useRippleEffect';
import { CheckBoxLayout } from '../checkbox-layout/check-box-layout';
import {
    forwardRef,
    useEffect,
    useImperativeHandle,
    useRef,
    useState,
} from 'react';

/**
 * Checkbox component
 ** description
 */

export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
    ({ centralRipple, ...props }, ref) => {
        const [isActive, setIsActive] = useState<boolean>(false),
            [checked, setChecked] = useState<boolean>(props.checked ?? false),
            ripplesRef = useRef(null),
            checkboxRef = useRef(null),
            events = useRippleEffect(ripplesRef, setIsActive);

        const extraClassStyles =
            `m3 m3-checkbox-label ${isActive === true ? 'visible' : ''}`.trimEnd();

        useImperativeHandle(ref, () => checkboxRef.current);

        useEffect(() => {
            setChecked(!checked);
        }, [checkboxRef.current?.checked]);

        return (
            <label {...events} className={extraClassStyles}>
                <CheckBoxLayout
                    {...props}
                    indeterminate={props.indeterminate}
                    ref={checkboxRef}
                    type={'checkbox'}
                />
                <span className={'m3 m3-checkbox-state'} />
                <span className={'m3 m3-checkbox-state-layer'} />
                <RippleArea
                    callback={setIsActive}
                    central={centralRipple}
                    className={'m3-checkbox-ripple-layer'}
                    ref={ripplesRef}
                />
                {props.children}
            </label>
        );
    },
);

Checkbox.propTypes = {
    indeterminate: bool,
    centralRipple: bool,
};
