import React, {FC, PropsWithChildren} from "react";
import {useFloating, offset, autoUpdate, FloatingPortal} from "@floating-ui/react";
import {useIsPresent} from "framer-motion";

export type ContentWithSidebarsProps = {
    leftSidebar?: React.ReactNode,
    rightSidebar?: React.ReactNode,
    width: number,
    height?: number,
    fitHeightToContent?: boolean,
    floatingZIndex?: number,
    leftSidebarPortal?: boolean,
}

export const ContentWithSidebars: FC<ContentWithSidebarsProps & PropsWithChildren> = ({
    children,
    leftSidebar,
    rightSidebar,
    width,
    height,
    fitHeightToContent = false,
    floatingZIndex = 10000,
    leftSidebarPortal = true,
}) => {
    const isPresent = useIsPresent();
    const shouldFitHeightToContent = fitHeightToContent && typeof height === 'number'
    const {refs: leftRefs, floatingStyles: leftFloatingStyles} = useFloating({
        placement: 'left-start',
        strategy: leftSidebarPortal ? 'fixed' : 'absolute',
        middleware: [offset(48)],
        whileElementsMounted: autoUpdate,
    });

    /*const {refs: rightRefs, floatingStyles: rightFloatingStyles} = useFloating({
        placement: 'right-start',
        middleware: [offset(48)],
        whileElementsMounted: autoUpdate,
    });*/

    const renderedLeftSidebar = leftSidebar && (
        <div ref={leftRefs.setFloating} style={{
            ...leftFloatingStyles,
            zIndex: floatingZIndex,
            opacity: isPresent ? 1 : 0,
            pointerEvents: isPresent ? 'auto' : 'none',
            transition: isPresent ? undefined : 'opacity 0.12s ease',
        }}>
            {leftSidebar}
        </div>
    )

    return <>
        <div className="relative" style={shouldFitHeightToContent ? {width, maxHeight: height} : {width, height}}>
            <div ref={(node) => {
                leftRefs.setReference(node);
                /*rightRefs.setReference(node);*/
            }} className={`relative w-full flex justify-center ${shouldFitHeightToContent ? 'overflow-y-auto max-h-full' : 'overflow-y-scroll h-full'}`}>
                {children}
            </div>
            {!leftSidebarPortal && renderedLeftSidebar}
        </div>
        {leftSidebarPortal && renderedLeftSidebar && (
            <FloatingPortal>
                {renderedLeftSidebar}
            </FloatingPortal>
        )}
        {/*rightSidebar && (
            <div ref={rightRefs.setFloating} style={rightFloatingStyles} className="z-50">
                {rightSidebar}
            </div>
        )*/}
    </>
}
