import {useLocation, useNavigate} from "react-router-dom";
import {useEffect, useState} from "react";
import {useLoadingSwitcher} from "../../../hooks/useLoading.jsx";
import {useFetch} from "../../../hooks/useFetch.js";
import {toast} from "react-toastify";
import {apiAxios, errFormater, getToastMessage} from "../../../utils/Tools.js";
import {AxiosError} from "../../../components/AxiosError.jsx";
import {Checkbox} from "../../../components/MemberCustomFiels.jsx";
import {ThreeDots} from "react-loader-spinner";
import {SearchBar} from "../../../components/SearchBar.jsx";
import {useTranslation} from "react-i18next";

export function ClubList() {
    const {hash} = useLocation();
    const {t} = useTranslation();
    const navigate = useNavigate();
    let page = Number(hash.substring(1));
    page = (page > 0) ? page : 1;

    const [clubData, setClubData] = useState([]);
    const [affiliationData, setAffiliationData] = useState([]);
    const [showAffiliationState, setShowAffiliationState] = useState(false);
    const [countryFilter, setCountryFilter] = useState("");
    const [lastSearch, setLastSearch] = useState("");

    const setLoading = useLoadingSwitcher()
    const {data, error, refresh} = useFetch(`/club/find?page=${page}`, setLoading, 1)


    useEffect(() => {
        refresh(`/club/find?page=${page}&search=${lastSearch}&country=${countryFilter}`);
    }, [hash, countryFilter]);

    useEffect(() => {
        if (!data)
            return;
        const data2 = [];
        for (const e of data.result) {
            data2.push({
                id: e.id,
                name: e.name,
                country: e.country,
                siret: e.siret,
                no_affiliation: e.no_affiliation,
                affiliation: showAffiliationState ? affiliationData.find(aff => (aff.id >= 0) ? Number(aff.club) === e.id : aff.club === e.state_id) : null
            })
        }
        setClubData(data2);
    }, [data, affiliationData]);

    useEffect(() => {
        if (!showAffiliationState)
            return;

        toast.promise(
            apiAxios.get(`/affiliation/current`), getToastMessage("club.toast.aff"))
            .then(data => {
                setAffiliationData(data.data);
            });
    }, [showAffiliationState]);

    const search = (search) => {
        if (search === lastSearch)
            return;
        setLastSearch(search);
        refresh(`/club/find?page=${page}&search=${search}&country=${countryFilter}`);
    }

    return <>
        <h2>{t('club', {count: 1})}</h2>
        <div>
            <div className="row">
                <div className="col-lg-9">
                    <SearchBar search={search}/>
                    {data
                        ? <MakeCentralPanel data={data} visibleclub={clubData} navigate={navigate} showAffiliationState={showAffiliationState}
                                            page={page}/>
                        : error
                            ? <AxiosError error={error}/>
                            : <Def/>
                    }
                </div>
                <div className="col-lg-3">
                    <div className="mb-4">
                        <div className="mb-2">
                            <button className="btn btn-primary" onClick={() => navigate("../affiliation/request")}>{t('demandeDaffiliationEnCours')}
                            </button>
                        </div>
                        <button className="btn btn-primary" onClick={() => navigate("new")}>{t('ajouterUnClub')}</button>
                    </div>
                    <div className="card mb-4">
                        <div className="card-header">{t('filtre')}</div>
                        <div className="card-body">
                            <FiltreBar showAffiliationState={showAffiliationState} setShowAffiliationState={setShowAffiliationState} data={data}
                                       countryFilter={countryFilter} setCountryFilter={setCountryFilter}/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </>
}

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

    const pages = []
    for (let i = 1; i <= data.page_count; i++) {
        pages.push(<li key={i} className={"page-item " + ((page === i) ? "active" : "")}>
            <span className="page-link" onClick={() => navigate("#" + i)}>{i}</span>
        </li>);
    }

    return <>
        <div className="mb-4">
            <small>{t("page_info_full", {
                line: ((page - 1) * data.page_size) + 1,
                tt_line: (page * data.page_size > data.result_count) ? data.result_count : (page * data.page_size),
                page: page,
                tt_page: data.page_count,
            })}</small>
            <div className="list-group">
                {visibleclub.map(club => (<MakeRow key={club.id} club={club} navigate={navigate} showAffiliationState={showAffiliationState}/>))}
            </div>
        </div>
        <div className="mb-4">
            <nav aria-label="Page navigation">
                <ul className="pagination justify-content-center">
                    <li className={"page-item" + ((page <= 1) ? " disabled" : "")}>
                        <span className="page-link" onClick={() => navigate("#" + (page - 1))}>&laquo;</span></li>
                    {pages}
                    <li className={"page-item" + ((page >= data.page_count) ? " disabled" : "")}>
                        <span className="page-link" onClick={() => navigate("#" + (page + 1))}>&raquo;</span></li>
                </ul>
            </nav>
        </div>
    </>
}

function MakeRow({club, showAffiliationState, navigate}) {
    const rowContent = <>
        <div className="row">
            <span className="col-auto">{club.no_affiliation ? String(club.no_affiliation).padStart(5, '0') : "-------"}</span>
            <div className="ms-2 col-auto">
                <div className="fw-bold">{club.name}</div>
            </div>
        </div>
        <small>{club.country}</small>
    </>

    if (showAffiliationState && club.affiliation != null) {
        return <div
            className={"list-group-item d-flex justify-content-between align-items-start list-group-item-action list-group-item-"
                + (club.affiliation.validate ? "success" : "warning")}
            onClick={() => navigate("" + club.id)}>{rowContent}</div>
    } else {
        return <div className="list-group-item d-flex justify-content-between align-items-start list-group-item-action"
                    onClick={() => navigate("" + club.id)}>
            {rowContent}
        </div>
    }
}

let allCountry = []

function FiltreBar({showAffiliationState, setShowAffiliationState, data, countryFilter, setCountryFilter}) {
    const {t} = useTranslation();

    useEffect(() => {
        if (!data)
            return;
        allCountry.push(...data.result.map((e) => e.country))
        allCountry = allCountry.filter((value, index, self) => self.indexOf(value) === index).filter(value => value != null).sort()
    }, [data]);

    return <div>
        <div className="mb-3">
            <Checkbox value={showAffiliationState} onChange={setShowAffiliationState}
                      label={t('afficherLétatDesAffiliation')}/>
        </div>
        <div className="mb-3">
            <select className="form-select" value={countryFilter} onChange={event => setCountryFilter(event.target.value)}>
                <option value="">{t('---ToutLesPays---')}</option>
                {allCountry && allCountry.map((value, index) => {
                    return <option key={index} value={value}>{value}</option>
                })
                }
            </select>
        </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>
}
