import {type ChangeEvent, useEffect, useRef} from "react";

type CheckBoxProps = {
    id: string;
    name: string;
    checked: boolean;
    onChange: (checked: boolean) => void;
    value?: string;
    label?: string;
    disabled?: boolean;
    indeterminate?: boolean;
};

export const CheckBox = ({
                             id,
                             name,
                             checked,
                             onChange,
                             value,
                             label,
                             disabled = false,
                             indeterminate = false,
                         }: CheckBoxProps) => {
    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        if (!inputRef.current) {
            return;
        }

        inputRef.current.indeterminate = indeterminate;
    }, [indeterminate]);

    const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
        onChange(event.target.checked);
    };

    return (
        <>
            <input
                ref={inputRef}
                type="checkbox"
                className="checkbox"
                id={id}
                name={name}
                value={value}
                checked={checked}
                disabled={disabled}
                onChange={handleChange}
            />
            <label htmlFor={id}>{label}</label>
        </>
    );
};
