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";

const vite_url = import.meta.env.VITE_URL;

export default function CompetitionManagerRoot() {
    return <>
        <h1>Compétition manager</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}) {
    return <>
        <div className="mb-4">
            <h4>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>
            <LoadingProvider>
                <Routes>
                    <Route path="/" element={<Home2 perm={perm}/>}/>
                    <Route path="/admin" element={<CMAdmin/>}/>
                    <Route path="/table" element={<CMTable/>}/>
                </Routes>
            </LoadingProvider>
        </CombsProvider>
    </WSProvider>
}

function WSStatus({setPerm}) {
    const [name, setName] = useState("")
    const [inWait, setInWait] = useState(false)
    const {isReady, wait_length, dispatch} = useWS();

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

    useEffect(() => {
        const welcomeListener = ({data}) => {
            setName(data.name)
            setPerm(data.perm)
        }
        dispatch({type: 'addListener', payload: {callback: welcomeListener, code: 'welcomeInfo'}})
        return () => dispatch({type: 'removeListener', payload: welcomeListener})
    }, [])

    return <div className="row">
        <h2 className="col">{name}</h2>
        <div className="col-auto" style={{margin: "auto 0", padding: 0}}>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();

    return <div className="row">
        <h4 className="col-auto" style={{margin: "auto 0"}}>Sélectionne les modes d'affichage</h4>
        <div className="col">
            {perm === "ADMIN" && <>
                <button className="btn btn-primary" onClick={() => nav("table")}>Table de marque</button>
                <button className="btn btn-primary ms-3" onClick={() => nav("admin")}>Administration</button>
            </>}
            {perm === "TABLE" && <>
                <button className="btn btn-primary" onClick={() => nav("table")}>Table de marque</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>
}
