import "../../style/actions/arrow_action.css"
import Draggable from "react-draggable"
import {RefObject, useRef} from "react"
import Xarrow, {useXarrow, Xwrapper} from "react-xarrows"

export interface ArrowActionProps {
    originRef: RefObject<HTMLDivElement>
    onArrowDropped: (arrowHead: DOMRect) => void
}

export default function ArrowAction({
                                        originRef,
                                        onArrowDropped,
                                    }: ArrowActionProps) {
    const arrowHeadRef = useRef<HTMLDivElement>(null)
    const updateXarrow = useXarrow()

    return (
        <div className="arrow-action">
            <div className="arrow-action-pin"/>

            <Xwrapper>
                <Draggable
                    nodeRef={arrowHeadRef}
                    onDrag={updateXarrow}
                    onStop={() => {
                        const headBounds =
                            arrowHeadRef.current!.getBoundingClientRect()
                        updateXarrow()
                        onArrowDropped(headBounds)
                    }}
                    position={{x: 0, y: 0}}>
                    <div
                        style={{
                            position: "absolute",
                        }}
                        ref={arrowHeadRef}
                        className="arrow-head-pick"
                        onMouseDown={updateXarrow}/>
                </Draggable>

                <div className={"arrow-head-xarrow"}>
                    <Xarrow
                        start={originRef}
                        end={arrowHeadRef}
                        startAnchor={"auto"}
                    />
                </div>
            </Xwrapper>
        </div>
    )
}
