import React, { ReactNode, useCallback, useRef, useState } from "react"

export interface SplitLayoutProps {
    children: [ReactNode, ReactNode]
    rightWidth: number
    onRightWidthChange: (w: number) => void
}

export default function SplitLayout({
    children,
    rightWidth,
    onRightWidthChange,
}: SplitLayoutProps) {
    const curtainRef = useRef<HTMLDivElement>(null)

    const resize = useCallback(
        (e: React.MouseEvent) => {
            const sliderPosX = e.clientX
            const curtainWidth =
                curtainRef.current!.getBoundingClientRect().width

            onRightWidthChange((sliderPosX / curtainWidth) * 100)
        },
        [curtainRef, onRightWidthChange],
    )

    const [resizing, setResizing] = useState(false)

    return (
        <div
            className={"curtain"}
            ref={curtainRef}
            style={{ display: "flex" }}
            onMouseMove={resizing ? resize : undefined}
            onMouseUp={() => setResizing(false)}>
            <div className={"curtain-left"} style={{ width: `${rightWidth}%` }}>
                {children[0]}
            </div>
            <div
                onMouseDown={() => setResizing(true)}
                style={{
                    width: 4,
                    height: "100%",
                    backgroundColor: "grey",
                    cursor: "col-resize",
                    userSelect: "none",
                }}></div>

            <div
                className={"curtain-right"}
                style={{ width: `${100 - rightWidth}%` }}>
                {children[1]}
            </div>
        </div>
    )
}
