import {useNavigate} from "react-router-dom";
import {useLoadingSwitcher} from "../../hooks/useLoading.jsx";
import {useFetch} from "../../hooks/useFetch.js";
import {AxiosError} from "../../components/AxiosError.jsx";
import {ThreeDots} from "react-loader-spinner";
import {useTranslation} from "react-i18next";

export function ResultList() {
    const navigate = useNavigate();
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/result/list`, setLoading, 1)

    return <>
        <div>
            <div className="row">
                {data
                    ? <MakeCentralPanel data={data} navigate={navigate}/>
                    : error
                        ? <AxiosError error={error}/>
                        : <Def/>
                }
            </div>
        </div>
    </>
}

function MakeCentralPanel({data, navigate}) {
    const {t} = useTranslation();

    return <>
        <div className="mb-4">
            <h4>{t('competition', {count: data.length})}:</h4>
            <div className="list-group">
                {data.sort((a, b) => new Date(b[2].split('T')[0]) - new Date(a[2].split('T')[0])).map((o) => (
                    <li className="list-group-item list-group-item-action" key={o[0]}
                    onClick={() => navigate(`${o[0]}`)}>{o[1]}</li>))}
            </div>
        </div>
    </>
}

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