import {
    CSSProperties,
    Dispatch,
    SetStateAction,
    useCallback,
    useRef,
    useState,
} from "react"
import "../style/editor.css"
import TitleInput from "../components/TitleInput"
import { BasketCourt } from "../components/editor/BasketCourt"

import { Rack } from "../components/Rack"
import { PlayerPiece } from "../components/editor/PlayerPiece"

import { Player } from "../tactic/Player"
import { Tactic, TacticContent } from "../tactic/Tactic"
import { fetchAPI } from "../Fetcher"
import { Team } from "../tactic/Team"
import { calculateRatio } from "../Utils"
import SavingState, {
    SaveState,
    SaveStates,
} from "../components/editor/SavingState"

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

export interface EditorViewProps {
    tactic: Tactic
    onContentChange: (tactic: TacticContent) => Promise<boolean>
    onNameChange: (name: string) => Promise<boolean>
}

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

export default function Editor({
    id,
    name,
    content,
}: {
    id: number
    name: string
    content: string
}) {
    return (
        <EditorView
            tactic={{ name, id, content: JSON.parse(content) }}
            onContentChange={(content: TacticContent) =>
                fetchAPI(`tactic/${id}/save`, { content }).then((r) => r.ok)
            }
            onNameChange={(name: string) =>
                fetchAPI(`tactic/${id}/edit/name`, { name }).then((r) => r.ok)
            }
        />
    )
}

function EditorView({
    tactic: { name, content: initialContent },
    onContentChange,
    onNameChange,
}: EditorViewProps) {
    const [style, setStyle] = useState<CSSProperties>({})
    const [content, setContent, saveState] = useContentState(
        initialContent,
        (content) =>
            onContentChange(content).then((success) =>
                success ? SaveStates.Ok : SaveStates.Err,
            ),
    )
    const [allies, setAllies] = useState(
        getRackPlayers(Team.Allies, content.players),
    )
    const [opponents, setOpponents] = useState(
        getRackPlayers(Team.Opponents, content.players),
    )

    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 { x, y } = calculateRatio(refBounds, courtBounds)

        setContent((content) => {
            return {
                players: [
                    ...content.players,
                    {
                        team: element.team,
                        role: element.key,
                        rightRatio: x,
                        bottomRatio: y,
                    },
                ],
            }
        })
    }

    return (
        <div id="main-div">
            <div id="topbar-div">
                <div id="topbar-left">
                    LEFT
                    <SavingState state={saveState} />
                </div>
                <div id="title-input-div">
                    <TitleInput
                        style={style}
                        default_value={name}
                        on_validated={(new_name) => {
                            onNameChange(new_name).then((success) => {
                                setStyle(success ? {} : ERROR_STYLE)
                            })
                        }}
                    />
                </div>
                <div id="topbar-right">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={content.players}
                            onPlayerChange={(player) => {
                                setContent((content) => ({
                                    players: toSplicedPlayers(
                                        content.players,
                                        player,
                                        true,
                                    ),
                                }))
                            }}
                            onPlayerRemove={(player) => {
                                setContent((content) => ({
                                    players: toSplicedPlayers(
                                        content.players,
                                        player,
                                        false,
                                    ),
                                }))
                                let setter
                                switch (player.team) {
                                    case Team.Opponents:
                                        setter = setOpponents
                                        break
                                    case Team.Allies:
                                        setter = setAllies
                                }
                                setter((players) => [
                                    ...players,
                                    {
                                        team: player.team,
                                        pos: player.role,
                                        key: player.role,
                                    },
                                ])
                            }}
                        />
                    </div>
                </div>
            </div>
        </div>
    )
}

function getRackPlayers(team: Team, players: Player[]): RackedPlayer[] {
    return ["1", "2", "3", "4", "5"]
        .filter(
            (role) =>
                players.findIndex((p) => p.team == team && p.role == role) ==
                -1,
        )
        .map((key) => ({ team, key }))
}

function useContentState<S>(
    initialContent: S,
    saveStateCallback: (s: S) => Promise<SaveState>,
): [S, Dispatch<SetStateAction<S>>, SaveState] {
    const [content, setContent] = useState(initialContent)
    const [savingState, setSavingState] = useState(SaveStates.Ok)

    const setContentSynced = useCallback((newState: SetStateAction<S>) => {
        setContent((content) => {
            const state =
                typeof newState === "function"
                    ? (newState as (state: S) => S)(content)
                    : newState
            if (state !== content) {
                setSavingState(SaveStates.Saving)
                saveStateCallback(state)
                    .then(setSavingState)
                    .catch(() => setSavingState(SaveStates.Err))
            }
            return state
        })
    }, [saveStateCallback])

    return [content, setContentSynced, savingState]
}

function toSplicedPlayers(
    players: Player[],
    player: Player,
    replace: boolean,
): Player[] {
    const idx = players.findIndex(
        (p) => p.team === player.team && p.role === player.role,
    )

    return players.toSpliced(idx, 1, ...(replace ? [player] : []))
}
