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 { useCallback } from "react"
import { useAppFetcher, useUser } from "../App.tsx"
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()
    const fetcher = useAppFetcher()
    const [user] = useUser()

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

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

                if (response.status === 401) {
                    // if unauthorized
                    navigate("/login")
                    return
                }

                const { id } = await response.json()
                navigate(`/tactic/${id}/edit`)
            }, [courtType, fetcher, navigate, user])}>
            <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>
    )
}
