import { twMerge } from 'tailwind-merge';
import style from '../../../style';
import clsx from 'clsx';
import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';

export interface CheckBoxProps extends React.InputHTMLAttributes<HTMLInputElement> {
    /**
     * Input Ref .
     */
    ref?: React.Ref<HTMLInputElement>;

    /**
     * Button variation that will switch between styles for the Checkbox .
     */
    variation?: 'initial' | 'default' | 'primary' | 'secondary';

    /**
     * Indeterminate state of the Checkbox.
     */
    indeterminate?: boolean;
}

const CheckBox: React.FC<CheckBoxProps> = forwardRef((props, ref) => {
    const { className, variation, disabled, indeterminate } = props;

    const inputRef = useRef<HTMLInputElement | null>(null);

    // Expose the input ref to the parent component.
    useImperativeHandle(ref, () => inputRef.current!);

    // Set the indeterminate state.
    useEffect(() => {
        if (inputRef.current) {
            inputRef.current.indeterminate = !!indeterminate;
        }
    }, [indeterminate]);

    const initialCss = style.checkbox.init;

    const disabledCss = disabled ? ' opacity-70 cursor-not-allowed ' : '';

    const variationClasses = clsx({
        [style.checkbox.default]: variation === 'default',
        [style.checkbox.primary]: variation === 'primary',
        [style.checkbox.secondary]: variation === 'secondary',
    });

    const classesMerged = `${initialCss} ${variationClasses} ${className ? className : ''} ${disabledCss} `;

    return <input type="checkbox" {...props} ref={inputRef} className={`${twMerge(classesMerged)}`} />;
});

CheckBox.defaultProps = {
    variation: 'initial',
};

export default CheckBox;
