import "../style/theme/default.css"
import "../style/new_tactic_panel.css"

import plainCourt from "../assets/court/full_court.svg"
import halfCourt from "../assets/court/half_court.svg"
import { CourtType } from "../model/tactic/Tactic.ts"
import { startTransition, useCallback } from "react"
import { fetchAPI } from "../Fetcher.ts"
import { getSession } from "../api/session.ts"
import { useNavigate } from "react-router-dom"

export const DEFAULT_TACTIC_NAME = "Nouvelle tactique"

export default function NewTacticPage() {
    return (
        <div id={"panel-root"}>
            <div id={"panel-top"}>
                <p>Selectionnez un terrain</p>
            </div>
            <div id={"panel-choices"}>
                <div id={"panel-buttons"}>
                    <CourtKindButton
                        name="Terrain complet"
                        image={plainCourt}
                        courtType={"PLAIN"}
                    />
                    <CourtKindButton
                        name="Demi-terrain"
                        image={halfCourt}
                        courtType={"HALF"}
                    />
                </div>
            </div>
        </div>
    )
}

function CourtKindButton({
    name,
    image,
    courtType,
}: {
    name: string
    image: string
    courtType: CourtType
}) {

    const navigate = useNavigate()

    return (
        <div
            className="court-kind-button"
            onClick={useCallback(async () => {
                // if user is not authenticated
                if (!getSession().auth) {
                    startTransition(() => {
                        navigate(`/tactic/edit-guest`)
                    })
                }

                const response = await fetchAPI(
                    "tactics",
                    {
                        name: DEFAULT_TACTIC_NAME,
                        courtType,
                    },
                    "POST",
                )

                const { id } = await response.json()
                startTransition(() => {
                    navigate(`/tactic/${id}/edit`)
                })
            }, [courtType, navigate])}>
            <div className="court-kind-button-top">
                <div className="court-kind-button-image-div">
                    <img
                        src={image}
                        alt={name}
                        className="court-kind-button-image"
                    />
                </div>
            </div>
            <div className="court-kind-button-bottom">
                <p className="court-kind-button-name">{name}</p>
            </div>
        </div>
    )
}
