import {Route, Routes, useNavigate, useParams} from "react-router-dom";
import {LoadingProvider, useLoadingSwitcher} from "../../../hooks/useLoading.jsx";
import {useEffect, useState} from "react";
import {useWS, WSProvider} from "../../../hooks/useWS.jsx";
import {ColoredCircle} from "../../../components/ColoredCircle.jsx";
import {CMAdmin} from "./CMAdmin.jsx";
import {CombsProvider} from "../../../hooks/useComb.jsx";
import {CMTable} from "./CMTable.jsx";
import {ThreeDots} from "react-loader-spinner";
import {AxiosError} from "../../../components/AxiosError.jsx";
import {useFetch} from "../../../hooks/useFetch.js";
import {useTranslation} from "react-i18next";
import {CardsProvider} from "../../../hooks/useCard.jsx";
import AudioEncoder from "../../../components/cm/AudioEncoder.jsx";

const vite_url = import.meta.env.VITE_URL;

export default function CompetitionManagerRoot() {
    const {t} = useTranslation("cm");
    return <>
        <h1>{t('compétitionManager')}</h1>
        <LoadingProvider>
            <Routes>
                <Route path="/" element={<Home/>}/>
                <Route path="/:compUuid/*" element={<HomeComp/>}/>
            </Routes>
        </LoadingProvider>
    </>
}

function Home() {
    const navigate = useNavigate();
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/competition/admin/all/INTERNAL/table`, setLoading, 1)

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

function MakeCentralPanel({data, navigate}) {
    const {t} = useTranslation("cm");
    return <>
        <div className="mb-4">
            <h4>{t('compétition')}:</h4>
            <div className="list-group">
                {data.sort((a, b) => new Date(b.date.split('T')[0]) - new Date(a.date.split('T')[0])).map((o) => (
                    <li className="list-group-item list-group-item-action" key={o.id}
                        onClick={__ => navigate(o.uuid)}>{o.name}</li>))}
            </div>
        </div>
    </>
}

function HomeComp() {
    let {compUuid} = useParams();
    const [perm, setPerm] = useState("")

    const messageHandler = msg => {
        console.log("Received WS message:", msg);
    }

    return <WSProvider url={`${vite_url.replace('http', 'ws')}/api/ws/competition/${compUuid}`} onmessage={messageHandler}>
        <WSStatus setPerm={setPerm}/>
        <CombsProvider>
            <CardsProvider>
                <LoadingProvider>
                    <Routes>
                        <Route path="/" element={<Home2 perm={perm}/>}/>
                        <Route path="/admin" element={<CMAdmin compUuid={compUuid}/>}/>
                        <Route path="/table" element={<CMTable/>}/>
                        <Route path="/view/audio" element={<AudioEncoder/>}/>
                    </Routes>
                </LoadingProvider>
            </CardsProvider>
        </CombsProvider>
    </WSProvider>
}

function WSStatus({setPerm}) {
    const [inWait, setInWait] = useState(false)
    const {isReady, wait_length, welcomeData} = useWS();
    const {t} = useTranslation("cm");

    useEffect(() => {
        const timer = setInterval(() => {
            setInWait(Object.keys(wait_length.current).length > 0);
        }, 250);
        return () => clearInterval(timer);
    }, []);

    useEffect(() => {
        setPerm(welcomeData.perm)
    }, [welcomeData])

    return <div className="row" style={{marginRight: "inherit"}}>
        <h2 className="col">{welcomeData.name}</h2>
        <div className="col-auto" style={{margin: "auto 0", padding: 0}}>{t('serveur')}: <ColoredCircle
            color={isReady ? (inWait ? "#ffad32" : "#00c700") : "#e50000"}/>
        </div>
        <div className="col-auto " id="actionMenu" style={{verticalAlign: "center", textAlign: "center", margin: "auto 0", padding: 0}}></div>
    </div>
}

function Home2({perm}) {
    const nav = useNavigate();
    const {t} = useTranslation("cm");

    return <div className="row">
        <h4 className="col-auto" style={{margin: "auto 0"}}>{t('sélectionneLesModesDaffichage')}</h4>
        <div className="col">
            {perm === "ADMIN" && <>
                <button className="btn btn-primary" onClick={() => nav("table")}>{t('secrétariatsDeLice')}</button>
                <button className="btn btn-primary ms-3" onClick={() => nav("admin")}>{t('administration')}</button>
            </>}
            {perm === "TABLE" && <>
                <button className="btn btn-primary" onClick={() => nav("table")}>{t('secrétariatsDeLice')}</button>
            </>}
        </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>
}
