import { useState, useCallback, useEffect } from "react";

const useSidebarResize = (initialWidth = 250) => {
    const [sidebarWidth, setSidebarWidth] = useState(initialWidth);
    const [isResizing, setIsResizing] = useState(false);

    const startResizing = useCallback((e) => {
        e.preventDefault();
        setIsResizing(true);
    }, []);

    const resize = useCallback((e) => {
        if (isResizing) {
            const newWidth = e.clientX;
            if (newWidth > 100 && newWidth < 400) {
                setSidebarWidth(newWidth);
            }
        }
    }, [isResizing]);

    const stopResizing = useCallback(() => {
        setIsResizing(false);
    }, []);

    useEffect(() => {
        const handleMouseMove = (e) => resize(e);
        const handleMouseUp = () => stopResizing();

        if (isResizing) {
            window.addEventListener("mousemove", handleMouseMove);
            window.addEventListener("mouseup", handleMouseUp);
        }

        return () => {
            window.removeEventListener("mousemove", handleMouseMove);
            window.removeEventListener("mouseup", handleMouseUp);
        };
    }, [isResizing, resize, stopResizing]);

    return { sidebarWidth, startResizing };
};

export default useSidebarResize;