import { forwardRef, useEffect, useRef } from 'react';

interface CheckboxCellProps extends React.InputHTMLAttributes<HTMLInputElement> {
  isSelected?: boolean | 'mixed';
  isIndeterminate?: boolean;
}

const CellCheckbox = forwardRef(
  ({ isIndeterminate, isSelected, ...props }: CheckboxCellProps, ref) => {
    const checkboxRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
      if (typeof ref === 'function') {
        ref(checkboxRef.current);
      } else if (ref) {
        ref.current = checkboxRef.current;
      }
    }, [ref]);

    useEffect(() => {
      if (checkboxRef.current) {
        checkboxRef.current.indeterminate = isIndeterminate ?? false;
      }
    }, [isIndeterminate]);

    return (
      <div className="custom-checkbox text-center">
        <input {...props} ref={checkboxRef} type="checkbox" />
        <div className="box bg-neutral-50">
          <svg
            className={`checkmark ${isSelected ? 'visible' : 'hidden'}`}
            aria-hidden="true"
            role="presentation"
            viewBox="0 0 17 18"
          >
            <polyline points="1 9 7 14 15 4" />
          </svg>
          <svg
            className={`indeterminate-mark ${isIndeterminate ? 'visible' : 'hidden'}`}
            aria-hidden="true"
            role="presentation"
            stroke="currentColor"
            strokeWidth="3"
            viewBox="0 0 24 24"
          >
            <line x1="3" x2="21" y1="12" y2="12" />
          </svg>
        </div>
      </div>
    );
  },
);

CellCheckbox.displayName = 'CellCheckbox';

export default CellCheckbox;
