import React, {FC, PropsWithChildren} from "react";
import {Position} from "@xyflow/system";
import {Handle, HandleProps} from "./tree/Handle";
import {NodeProps} from "@xyflow/react";
import {Anchor} from "./tree/store";

export type NodeWithAnchorsProps = Pick<HandleProps, 'color'> & {
    left?: boolean,
    right?: boolean,
    leftX?: number,
    rightX?: number
    // will give a bigger z-index to the handles then the content
    handlesOverContent?: boolean,
    centerExtraAnchor?: boolean
}

export const NodeWithAnchors: FC<NodeWithAnchorsProps & Pick<NodeProps, 'data'> & PropsWithChildren> = ({
                                                                                                            data,
                                                                                                            left = true,
                                                                                                            right = true,
                                                                                                            color,
                                                                                                            children,
                                                                                                            leftX,
                                                                                                            rightX,
                                                                                                            handlesOverContent,
                                                                                                            centerExtraAnchor = true
                                                                                                        }) => {
    const sourceAnchor = data?.sourceAnchor as Anchor || undefined

    return <div className="relative flex items-center">
        {left && <Handle id={`left`} type={'target'} position={Position.Left} color={color} x={leftX}
                 bringToFront={handlesOverContent}/>}
        <div className={centerExtraAnchor? 'flex flex-col items-center' : ''}>
            <div className={!handlesOverContent ? 'relative z-10' : ''}>
                {children}
            </div>
            {sourceAnchor?.id && <Handle id={sourceAnchor?.id} type={'source'} position={sourceAnchor?.position}
                                         color={color} x={rightX} bringToFront={handlesOverContent}/>}
        </div>
        {right && <Handle id={sourceAnchor?.id || `right`} type={'source'} position={sourceAnchor?.position || Position.Right}
                 color={color} x={rightX} bringToFront={handlesOverContent}/>}
    </div>;
}
