import {useRequestWS} from "../../hooks/useWS.jsx";
import {AxiosError} from "../AxiosError.jsx";
import {useTranslation} from "react-i18next";
import React, {useId} from "react";

export function ListPresetSelect({disabled, value, onChange, returnId = true}) {
    const id = useId()
    const {data, error} = useRequestWS("listPreset", {}, null);
    const {t} = useTranslation();
    return <>
        {data
            ? <div className="mb-3">
                <label className="form-label" htmlFor={id}>{t('catégorie')}</label>
                <select className="form-select" id={id} disabled={disabled}
                        value={returnId ? value : (value ? value.id : -1)}
                        onChange={e => {
                            if (returnId) {
                                onChange(Number(e.target.value))
                            } else {
                                onChange(data.find(c => c.id === Number(e.target.value)))
                            }
                        }}>
                    <option value={-1}>{t('sélectionner...')}</option>
                    {data.sort((a, b) => a.name.localeCompare(b.name)).map(o => (<option key={o.id} value={o.id}>{o.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('catégorie')}</label>
        <select className="form-select" id="inputGroupSelect02"
                defaultValue={t('chargement...')}>
            <option>{t('chargement...')}</option>
        </select>
    </div>;
}
