'use client';

import React, {
    forwardRef,
    useEffect,
    useImperativeHandle,
    useRef,
} from 'react';
import { bool, string } from 'prop-types';
import { CheckboxLayoutProps } from './checkbox-layout.types';

export const CheckBoxLayout = forwardRef<HTMLInputElement, CheckboxLayoutProps>(
    ({ indeterminate, typeInput, type, ...props }, ref) => {
        const checkboxRef = useRef<HTMLInputElement>(null);

        useEffect(() => {
            checkboxRef.current.indeterminate = indeterminate === true;
        }, []);

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

        const classesType = typeInput || type;

        const classes =
            props.className !== undefined
                ? `m3 m3-${type} ${props.className}`
                : `m3 m3-${classesType}`;

        return (
            <input
                ref={checkboxRef}
                {...props}
                className={classes.trimEnd()}
                type={type}
            />
        );
    },
);

CheckBoxLayout.propTypes = {
    indeterminate: bool,
    typeInput: string,
    type: string,
};
