import { clsx } from 'clsx';
import { InputHTMLAttributes, forwardRef, useEffect, useImperativeHandle, useRef } from 'react';

import { useInputAttributes } from '../inputs/contexts';

export type CheckboxButtonProps = InputHTMLAttributes<HTMLInputElement> & {
  /** @default false */
  indeterminate?: boolean;
};

const CheckboxButton = forwardRef<HTMLInputElement, CheckboxButtonProps>(function CheckboxButton(
  { checked, indeterminate = false, className, disabled, onChange, ...rest },
  reference,
) {
  const inputAttributes = useInputAttributes();

  const internalRef = useRef<HTMLInputElement>(null);

  useImperativeHandle(reference, () => internalRef.current ?? ({} as HTMLInputElement));

  useEffect(() => {
    if (internalRef.current) {
      // eslint-disable-next-line functional/immutable-data
      internalRef.current.indeterminate = indeterminate;
    }
  }, [indeterminate, reference]);

  return (
    <span className={clsx('np-checkbox-button', className, disabled && 'disabled')}>
      <input
        {...inputAttributes}
        {...rest}
        ref={reference ?? internalRef}
        type="checkbox"
        disabled={disabled}
        checked={checked}
        onChange={onChange}
      />
      <span className="tw-checkbox-button">
        <span className="tw-checkbox-check" />
        <span className="np-tw-checkbox-indeterminate" />
      </span>
    </span>
  );
});

export default CheckboxButton;
