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

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)
    const {t} = useTranslation();

    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>{t('sélectionner...')}</option>
                    {na && <option value={-1}>{t('--NonLicencier--')}</option>}
                    {data.map(club => (<option key={club.id} value={club.id}>{club.name}</option>))}
                </select>
            </div>
            : error
                ? <AxiosError error={error}/>
                : <Def/>
        }
    </>
}

function Def() {
    const {t} = useTranslation();

    return <div className="input-group mb-3">
        <label className="input-group-text" id="inputGroupSelect02">{t("club", {count: 1})}</label>
        <select className="form-select" id="inputGroupSelect02"
                defaultValue={t('chargement...')}>
            <option>{t('chargement...')}</option>
        </select>
    </div>;
}
