import { KeyboardEventHandler, RefObject, useRef } from "react"
import Draggable from "react-draggable"
import { BallPiece } from "./BallPiece"
import { NULL_POS, Pos } from "../../geo/Pos"
import { Ball } from "../../model/tactic/CourtObjects"

export interface CourtBallProps {
    ball: Ball
}

export interface EditableCourtBallProps extends CourtBallProps {
    onPosValidated: (rect: DOMRect) => void
    onRemove: () => void
}

export function CourtBall({
    onPosValidated,
    ball,
    onRemove,
}: EditableCourtBallProps) {
    const pieceRef = useRef<HTMLDivElement>(null)

    if (ball.frozen) {
        return courtBallPiece(ball.pos)
    }

    return (
        <Draggable
            onStop={() =>
                onPosValidated(pieceRef.current!.getBoundingClientRect())
            }
            position={NULL_POS}
            nodeRef={pieceRef}>
            {courtBallPiece(ball.pos, pieceRef, (e) => {
                if (e.key == "Delete") onRemove()
            })}
        </Draggable>
    )
}

interface CourtBallPieceProps {
    pos: Pos
}

export function CourtBallPiece({ pos }: CourtBallPieceProps) {
    return courtBallPiece(pos)
}

function courtBallPiece(
    { x, y }: Pos,
    pieceRef?: RefObject<HTMLDivElement>,
    onKeyUp?: KeyboardEventHandler,
) {
    return (
        <div
            className={"ball-div"}
            ref={pieceRef}
            tabIndex={0}
            onKeyUp={onKeyUp}
            style={{
                position: "absolute",
                left: `${x * 100}%`,
                top: `${y * 100}%`,
            }}>
            <BallPiece />
        </div>
    )
}
