import {CSSProperties, ReactElement, RefObject, useRef, useState} from "react";
import "../style/editor.css";
import TitleInput from "../components/TitleInput";
import {API} from "../Constants";
import {BasketCourt} from "../components/editor/BasketCourt";

import {Rack} from "../components/Rack";
import {PlayerPiece} from "../components/editor/PlayerPiece";
import {Player} from "../data/Player";

const ERROR_STYLE: CSSProperties = {
    borderColor: "red"
}

export default function Editor({id, name}: { id: number, name: string }) {
    const [style, setStyle] = useState<CSSProperties>({});

    const positions = ["PG", "SG", "SF", "PF", "C"]
    const [team, setTeams] = useState(
        positions.map(pos => <PlayerPiece key={pos} text={pos}/>)
    )
    const [opponents, setOpponents] = useState(
        positions.map(pos => <PlayerPiece key={pos} text={pos}/>)
    )

    const [players, setPlayers] = useState<Player[]>([]);
    const courtDivContentRef = useRef<HTMLDivElement>(null);

    const canDetach = (ref: RefObject<HTMLDivElement>) => {
        const refBounds = ref.current!.getBoundingClientRect();
        const courtBounds = courtDivContentRef.current!.getBoundingClientRect();

        // check if refBounds overlaps courtBounds
        return !(
            refBounds.top > courtBounds.bottom ||
            refBounds.right < courtBounds.left ||
            refBounds.bottom < courtBounds.top ||
            refBounds.left > courtBounds.right
        );
    }

    const onElementDetach = (ref: RefObject<HTMLDivElement>, element: ReactElement) => {
        const refBounds = ref.current!.getBoundingClientRect();
        const courtBounds = courtDivContentRef.current!.getBoundingClientRect();

        const relativeXPixels = refBounds.x - courtBounds.x;
        const relativeYPixels = refBounds.y - courtBounds.y;

        const xPercent = relativeXPixels / courtBounds.width;
        const yPercent = relativeYPixels / courtBounds.height;

        setPlayers(players => {
            return [...players, {
                id: players.length,
                position: element.props.text,
                right_percentage: xPercent,
                bottom_percentage: yPercent
            }]
        })
    }

    return (
        <div id="main-div">
            <div id="topbar-div">
                <div>LEFT</div>
                <TitleInput style={style} default_value={name} on_validated={new_name => {
                    fetch(`${API}/tactic/${id}/edit/name`, {
                        method: "POST",
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            name: new_name,
                        })
                    }).then(response => {
                        if (response.ok) {
                            setStyle({})
                        } else {
                            setStyle(ERROR_STYLE)
                        }
                    })
                }}/>
                <div>RIGHT</div>
            </div>
            <div id="edit-div">
                <div id="racks">
                    <Rack id="team-rack"
                          objects={[team, setTeams]}
                          canDetach={canDetach}
                          onElementDetached={onElementDetach}/>
                    <Rack id="opponent-rack"
                          objects={[opponents, setOpponents]}
                          canDetach={canDetach}
                          onElementDetached={onElementDetach}/>
                </div>
                <div id="court-div">
                    <div ref={courtDivContentRef}>
                        <BasketCourt players={players}/>
                    </div>
                </div>
            </div>
        </div>
    )
}
