import React, { useState, useRef, useEffect, useCallback } from 'react';

const ColumnResizer = ({ reportDragDeltaX }) => {
  const [isDragging, setIsDragging] = useState(false);
  const lastXRef = useRef(0);

  const handleMouseDown = (e) => {
    if (e.button !== 0) return;
    e.preventDefault();
    setIsDragging(true);
    lastXRef.current = e.clientX;
  };

  const handleMouseMove = useCallback(
    (e) => {
      if (!isDragging) return;

      const deltaX = e.clientX - lastXRef.current;

      if (deltaX !== 0) {
        reportDragDeltaX?.(deltaX);
        lastXRef.current = e.clientX;
      }
    },
    [isDragging, reportDragDeltaX],
  );

  const handleMouseUp = useCallback(() => {
    setIsDragging(false);
  }, []);

  useEffect(() => {
    if (isDragging) {
      window.addEventListener('mousemove', handleMouseMove);
      window.addEventListener('mouseup', handleMouseUp);
    }

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging, handleMouseMove, handleMouseUp]);

  return (
    <div
      onMouseDown={handleMouseDown}
      style={{
        position: 'absolute',
        right: 0,
        top: 0,
        width: '4px',
        height: '100%',
        backgroundColor: 'transparent',
        cursor: 'col-resize',
        userSelect: 'none',
      }}
    />
  );
};

export default ColumnResizer;
