import React, { useState, useCallback, useEffect, useRef } from 'react';
import './style.less';

interface ResizableContainerProps {
    width?: number;
    minWidth?: number;
    maxWidth?: number;
    height?:string;
}

const ResizableContainer: React.FC<React.PropsWithChildren<ResizableContainerProps>> = ({
    width = 250,
    minWidth = 100,
    maxWidth = 800,
    height = '800px',
    children,
}) => {
    const [containerWidth, setContainerWidth] = useState(width);
    const isResizing = useRef(false);

    const handleMouseMove = useCallback((e: MouseEvent) => {
        if (isResizing.current) {
            const newWidth = Math.min(Math.max(e.clientX, minWidth), maxWidth);
            setContainerWidth(newWidth);
        }
    }, [minWidth, maxWidth]);

    const handleMouseUp = useCallback(() => {
        isResizing.current = false;
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
    }, [handleMouseMove]);

    const handleMouseDown = useCallback(() => {
        isResizing.current = true;
        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);
    }, [handleMouseMove, handleMouseUp]);

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

    useEffect(()=>{
        setContainerWidth(width);
    },[width])

    return (
        <div className="ResizableContainer">
            <div className="resizable" style={{ width: `${containerWidth}px`,height: `${height}` }}>
                {children}
            </div>
            <div className="resizer" onMouseDown={handleMouseDown} />
        </div>
    );
};

export default ResizableContainer;
