import {CSSProperties, 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";
import {Team} from "../data/Team";

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

/**
 * information about a player that is into a rack
 */
interface RackedPlayer {
    team: Team,
    key: string,
}

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

    const positions = ["1", "2", "3", "4", "5"]
    const [allies, setAllies] = useState(
        positions.map(key => ({team: Team.Allies, key}))
    )
    const [opponents, setOpponents] = useState(
        positions.map(key => ({team: Team.Opponents, key}))
    )

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

    const canDetach = (ref: HTMLDivElement) => {
        const refBounds = ref.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 onPieceDetach = (ref: HTMLDivElement, element: RackedPlayer) => {
        const refBounds = ref.getBoundingClientRect();
        const courtBounds = courtDivContentRef.current!.getBoundingClientRect();

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

        const xRatio = relativeXPixels / courtBounds.width;
        const yRatio = relativeYPixels / courtBounds.height;

        setPlayers(players => {
            return [...players, {
                id: players.length,
                team: element.team,
                role: element.key,
                rightRatio: xRatio,
                bottomRatio: yRatio
            }]
        })
    }

    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="allies-rack"
                          objects={allies}
                          onChange={setAllies}
                          canDetach={canDetach}
                          onElementDetached={onPieceDetach}
                          render={({team, key}) => <PlayerPiece team={team} text={key} key={key}/>}/>
                    <Rack id="opponent-rack"
                          objects={opponents}
                          onChange={setOpponents}
                          canDetach={canDetach}
                          onElementDetached={onPieceDetach}
                          render={({team, key}) => <PlayerPiece team={team} text={key} key={key}/>}/>
                </div>
                <div id="court-div">
                    <div id="court-div-bounds" ref={courtDivContentRef}>
                        <BasketCourt
                            players={players}
                            onPlayerRemove={(player) => {
                                setPlayers(players => {
                                    const idx = players.indexOf(player)
                                    return players.toSpliced(idx, 1)
                                })
                                switch (player.team) {
                                    case Team.Opponents:
                                        setOpponents(opponents => (
                                            [...opponents, {
                                                team: player.team,
                                                pos: player.role,
                                                key: player.role
                                            }]
                                        ))
                                        break
                                    case Team.Allies:
                                        setAllies(allies => (
                                            [...allies, {
                                                team: player.team,
                                                pos: player.role,
                                                key: player.role
                                            }]
                                        ))
                                }
                            }}/>
                    </div>
                </div>
            </div>
        </div>
    )
}

