import {Route, Routes, useNavigate, useParams} from "react-router-dom";
import {LoadingProvider} 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";

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 nav = useNavigate();
    return <div>
        <h2>Home</h2>
        <button onClick={() => nav("d3dc76a6-2058-423a-b34b-6d15d7ae5848")}>Go comp</button>
    </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="/test" element={<Test2/>}/>
                </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"}}>Serveur: <ColoredCircle color={isReady ? (inWait ? "#ffad32" : "#00c700") : "#e50000"}/>
        </div>
    </div>
}

function Home2({perm}) {
    const nav = useNavigate();
    const {sendRequest} = useWS();

    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>
        <button onClick={() => {
            sendRequest("getAllMatch", 1156)
                .then(data => {
                    console.log("Received response for getAllMatch:", data);
                })
                .catch(err => {
                    console.error("Error in getAllMatch request:", err);
                })
        }}>Send Test
        </button>
        <button onClick={() => nav(-1)}>Go Back</button>
        <button onClick={() => nav("test")}>Go Test</button>
    </div>
}

function Test2() {
    let {compUuid} = useParams();
    const nav = useNavigate();
    return <div>
        <h2>Product ID: {compUuid}</h2>
        <button onClick={() => nav(-1)}>Go Back</button>
    </div>
}
