import {useNavigate, useParams} from "react-router-dom";
import {useLoadingSwitcher} from "../../hooks/useLoading.jsx";
import {useFetch} from "../../hooks/useFetch.js";
import {AxiosError} from "../../components/AxiosError.jsx";
import {useAuth} from "../../hooks/useAuth.jsx";
import {apiAxios, isClubAdmin} from "../../utils/Tools.js";
import {ThreeDots} from "react-loader-spinner";
import {useEffect, useState} from "react";
import {toast} from "react-toastify";

export function CompetitionView() {

    const {id} = useParams()
    const navigate = useNavigate();

    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/competition/${id}?light=true`, setLoading, 1)

    return <>
        <button type="button" className="btn btn-link" onClick={() => navigate("/competition")}>
            &laquo; retour
        </button>
        <div>
            {data ? <>
                    <MakeContent data={data}/>
                </>
                : error && <AxiosError error={error}/>
            }
        </div>
    </>
}

const inscText = (type) => {
    if (type === "FREE") {
        return "Libres"
    } else if (type === "CLUB_ADMIN") {
        return "Par les responsables de club"
    } else if (type === "ADMIN") {
        return "Par les administrateurs de la compétition"
    } else if (type === "HELLOASSO") {
        return "Sur la billetterie HelloAsso"
    }

    return ""
}

function MakeContent({data}) {
    const {userinfo} = useAuth()
    const navigate = useNavigate()

    return <div className="card mb-4">
        <div className="card-header">
            <h2 className="card-title" style={{textAlign: "center"}}>{data.name}</h2>
        </div>
        <div className="card-body">
            <p>{data.description}</p>
            <p><strong>Date
                :</strong> Du {new Date(data.date.split('T')[0]).toLocaleDateString()} au {new Date(data.toDate.split('T')[0]).toLocaleDateString()}
            </p>
            <p><strong>Lieu :</strong> {data.adresse}</p>
            <p><strong>Organisateur :</strong> {data.clubName}</p>
            <p><strong>Type d'inscription :</strong> {inscText(data.registerMode)}</p>
            {(data.registerMode === "FREE" || data.registerMode === "CLUB_ADMIN") &&
                <p><strong>Date d'inscription
                    :</strong> Du {new Date(data.startRegister.split('+')[0]).toLocaleString()} au {new Date(data.endRegister.split('+')[0]).toLocaleString()}
                </p>
            }

            {(data.registerMode === "FREE" || data.registerMode === "CLUB_ADMIN") && isClubAdmin(userinfo) &&
                <button type="button" className="btn btn-primary"
                        disabled={new Date() < new Date(data.startRegister.split('+')[0]) || new Date() > new Date(data.endRegister.split('+')[0])}
                        onClick={_ => navigate("/competition/" + data.id + "/club/register")}>Inscription</button>
            }
            {data.registerMode === "FREE" && !isClubAdmin(userinfo) &&
                <SelfRegister data2={data}/>
            }
            {data.registerMode === "HELLOASSO" &&
                <p><strong>Billetterie :</strong> <a
                    href={`https://www.helloasso.com/associations/${data.data1}/evenements/${data.data2}`} target="_blank"
                    rel="noopener noreferrer">{`https://www.helloasso.com/associations/${data.data1}/evenements/${data.data2}`}</a></p>
            }
        </div>
    </div>
}

function SelfRegister({data2}) {
    const {id} = useParams()
    const setLoading = useLoadingSwitcher()
    const {data, refresh, error} = useFetch(`/competition/${id}/register/user`, setLoading, 1)

    const [weight, setWeight] = useState("")
    const [cat, setCat] = useState(0)

    useEffect(() => {
        if (data && data.length > 0) {
            setWeight(data[0].weight || "")
            setCat(data[0].overCategory || 0)
        }
    }, [data]);

    const disabled = new Date() < new Date(data2.startRegister.split('+')[0]) || new Date() > new Date(data2.endRegister.split('+')[0])

    const handleUnregister = () => {
        if (window.confirm("Êtes-vous sûr de vouloir vous désinscrire ?")) {
            toast.promise(apiAxios.delete(`/competition/${id}/register/${data[0].id}/user`), {
                pending: "Désinscription en cours",
                success: "Désinscription réalisée",
                error: {
                    render({data}) {
                        return data.response.data || "Erreur"
                    }
                }
            }).finally(() => {
                refresh(`/competition/${id}/register/user`)
            })
        }
    }

    const sendSubmit = (new_state) => {
        toast.promise(apiAxios.post(`/competition/${id}/register/user`, new_state), {
            pending: "Enregistrement en cours",
            success: "Inscription réalisée",
            error: {
                render({data}) {
                    return data.response.data || "Combattant non trouvé"
                }
            }
        }).finally(() => {
            refresh(`/competition/${id}/register/user`)
        })
    }

    const handleSubmit = (e) => {
        sendSubmit({
            licence: 0, fname: "", lname: "", weight: weight, overCategory: cat, lockEdit: false, id: null
        })
    }

    return <>
        {data
            ? data.length > 0
                ? <div style={{textAlign: "right", maxWidth: "20em"}}>
                    <h4 style={{textAlign: "left"}}>Mon inscription</h4>
                    <div className="input-group mb-3">
                        <span className="input-group-text" id="weight">Poids (en kg)</span>
                        <input type="number" min={1} step={1} className="form-control" placeholder="42" aria-label="weight" disabled={disabled}
                               name="weight" aria-describedby="weight" value={weight} onChange={e => setWeight(e.target.value)}/>
                    </div>

                    <div style={{textAlign: "left"}}>Catégorie normalisée: {data[0].categorie}</div>
                    <div className="input-group mb-3">
                        <span className="input-group-text" id="categorie">Surclassement</span>
                        <select className="form-select" aria-label="categorie" name="categorie" value={cat} disabled={disabled}
                                onChange={e => setCat(Number(e.target.value))}>
                            <option value={0}>Aucun</option>
                            <option value={1}>+1 catégorie</option>
                            <option value={2}>+2 catégorie</option>
                        </select>
                    </div>

                    <div>
                        <button type="button" className="btn btn-danger" disabled={disabled} style={{marginRight: "0.5em"}}
                                onClick={handleUnregister}>Se désinscrire
                        </button>
                        <button type="button" className="btn btn-primary" disabled={disabled}
                                onClick={handleSubmit}>Enregister
                        </button>
                    </div>
                </div>
                : <button type="button" className="btn btn-primary" disabled={disabled} onClick={handleSubmit}>S'inscrire</button>
            : error
                ? <AxiosError error={error}/>
                : <Def/>
        }
    </>
}

function Def() {
    return <div className="list-group">
        <li className="list-group-item"><ThreeDots/></li>
    </div>
}
