import {LoadingProvider, useLoadingSwitcher} from "../hooks/useLoading.jsx";
import {useFetch} from "../hooks/useFetch.js";
import {AxiosError} from "./AxiosError.jsx";

export function ClubSelect({defaultValue, name, na = false, disabled = false}) {
    return <LoadingProvider>
        <ClubSelect_ defaultValue={defaultValue} name={name} na={na} disabled={disabled}/>
    </LoadingProvider>
}

function ClubSelect_({defaultValue, name, na, disabled}) {
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/club/no_detail`, setLoading, 1)

    return <>
        {data
            ? <div className="input-group mb-3">
                <label className="input-group-text" id="inputGroupSelect02">Club</label>
                <select className="form-select" id="inputGroupSelect02" disabled={disabled}
                        defaultValue={defaultValue ? defaultValue : -1} name={name}>
                    <option>Sélectionner...</option>
                    {na && <option value={-1}>-- Non licencier --</option>}
                    {data.map(club => (<option key={club.id} value={club.id}>{club.name}</option>))}
                </select>
            </div>
            : error
                ? <AxiosError error={error}/>
                : <Def/>
        }
    </>
}

function Def() {
    return <div className="input-group mb-3">
        <label className="input-group-text" id="inputGroupSelect02">Club</label>
        <select className="form-select" id="inputGroupSelect02"
                defaultValue="Chargement...">
            <option>Chargement...</option>
        </select>
    </div>;
}
