import { ReactElement, ReactNode, RefObject, useEffect, useState } from "react"
import { Action } from "../../model/tactic/Action"

import { CourtAction } from "./CourtAction"
import {
    ComponentId,
    CourtType,
    TacticComponent,
} from "../../model/tactic/Tactic"
import PlainCourt from "../../assets/court/full_court.svg?react"
import HalfCourt from "../../assets/court/half_court.svg?react"

export interface BasketCourtProps {
    components: TacticComponent[]
    parentComponents: TacticComponent[] | null
    previewAction?: ActionPreview | null

    renderComponent: (comp: TacticComponent, isFromParent: boolean) => ReactNode
    renderActions: (comp: TacticComponent, isFromParent: boolean) => ReactNode[]

    courtImage: ReactElement
    courtRef: RefObject<HTMLDivElement>
}

export interface ActionPreview extends Action {
    origin: ComponentId
    isInvalid: boolean
}

export function BasketCourt({
    components,
    parentComponents,
    previewAction,

    renderComponent,
    renderActions,

    courtImage,
    courtRef,
}: BasketCourtProps) {
    const [court, setCourt] = useState(courtRef.current)

    //force update once the court reference is set
    useEffect(() => {
        setCourt(courtRef.current)
    }, [courtRef])

    return (
        <div
            className="court-container"
            ref={courtRef}
            style={{ position: "relative" }}>
            {courtImage}

            {court && parentComponents?.map((i) => renderComponent(i, true))}
            {court && parentComponents?.flatMap((i) => renderActions(i, true))}

            {court && components.map((i) => renderComponent(i, false))}
            {court && components.flatMap((i) => renderActions(i, false))}

            {previewAction && (
                <CourtAction
                    courtRef={courtRef}
                    action={previewAction}
                    origin={previewAction.origin}
                    color={previewAction.isInvalid ? "red" : "black"}
                    isEditable={true}
                    //do nothing on interacted, not really possible as it's a preview arrow
                    onActionDeleted={() => {}}
                    onActionChanges={() => {}}
                />
            )}
        </div>
    )
}

export function Court({ courtType }: { courtType: CourtType }) {
    const CourtSvg = courtType === "PLAIN" ? PlainCourt : HalfCourt
    return (
        <div className="court-image-div">
            <CourtSvg className="court-image" />
        </div>
    )
}
