import {useNavigate, useParams} 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 {useEffect, useState} from "react";
import {DrawGraph} from "./DrawGraph.jsx";
import {TreeNode} from "../../utils/TreeUtils.js";
import {scoreToString} from "../../utils/CompetitionTools.js";

function CupImg() {
    return <img decoding="async" loading="lazy" width="16" height="16" className="wp-image-1635"
                style={{width: "16px"}} src="/img/171891.png"
                alt=""/>
}

export function ResultView() {
    const {uuid} = useParams()
    const navigate = useNavigate();
    const [resultShow, setResultShow] = useState(null)

    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/result/${uuid}`, setLoading, 1)

    return <>
        <button type="button" className="btn btn-link" onClick={() => navigate("/result")}>
            &laquo; retour
        </button>

        {data ? <MenuBar data={data} resultShow={resultShow} setResultShow={setResultShow}/>
            : error
                ? <AxiosError error={error}/>
                : <Def/>}

        <div className="row">
            <div className="col-auto">
                {resultShow && resultShow.type !== undefined && <PouleResult data={resultShow}/>
                    || resultShow && resultShow === "club" && <ClubResult uuid={uuid}/>
                    || resultShow && resultShow === "comb" && <CombResult uuid={uuid}/>}
            </div>
        </div>
    </>
}
// || resultShow && resultShow === "club_all" && <ClubAllResult uuid={uuid}/>

function MenuBar({data, resultShow, setResultShow}) {
    return <ul className="nav nav-tabs">
        <li className="nav-item dropdown">
            <a className={"nav-link dropdown-toggle my-1"} data-bs-toggle="dropdown" href="#"
               aria-current={(resultShow?.type !== undefined ? " page" : "false")} role="button" aria-expanded="false">Catégorie</a>
            <ul className="dropdown-menu">
                {data.map(item => <li><a key={item.name} className={"dropdown-item" + (resultShow === item ? " active" : "")}
                                         aria-current={(resultShow === item ? " page" : "false")} href="#" data-bs-toggle="collapse"
                                         onClick={_ => setResultShow(item)}>{item.name}</a></li>)}
            </ul>
        </li>
        <li className="nav-item">
            <a className={"nav-link my-1" + (resultShow === "club" ? " active" : "")} aria-current={(resultShow === "club" ? " page" : "false")}
               href="#" onClick={_ => setResultShow("club")}>Mon club</a>
        </li>
        <li className="nav-item">
            <a className={"nav-link my-1" + (resultShow === "comb" ? " active" : "")} aria-current={(resultShow === "comb" ? " page" : "false")}
               href="#" onClick={_ => setResultShow("comb")}>Combattants</a>
        </li>
    </ul>

    /*
        <li className="nav-item">
            <a className={"nav-link my-1" + (resultShow === "club_all" ? " active" : "")}
               aria-current={(resultShow === "club_all" ? " page" : "false")}
               href="#" onClick={_ => setResultShow("club_all")}>Clubs</a>
        </li>
     */
}

function BuildMatchArray({matchs}) {
    return <>
        <table className="table table-striped">
            <thead>
            <tr>
                <th scope="col" style={{textAlign: "center"}}>Rouge</th>
                <th scope="col" style={{textAlign: "center"}}></th>
                <th scope="col" style={{textAlign: "center"}}>Scores</th>
                <th scope="col" style={{textAlign: "center"}}></th>
                <th scope="col" style={{textAlign: "center"}}>Bleu</th>
            </tr>
            </thead>
            <tbody>
            {matchs.map((match, idx) => <tr key={idx}>
                <td style={{textAlign: "right"}}>{match.red}</td>
                <td style={{textAlign: "center"}}>{match.red_w ? <CupImg/> : ""}</td>
                <td style={{textAlign: "center"}}>{scoreToString(match.score)}</td>
                <td style={{textAlign: "center"}}>{match.blue_w ? <CupImg/> : ""}</td>
                <td style={{textAlign: "left"}}>{match.blue}</td>
            </tr>)}
            </tbody>
        </table>
    </>
}

function BuildRankArray({rankArray}) {
    return <>
        <table className="table table-striped">
            <thead>
            <tr>
                <th scope="col" style={{textAlign: "center"}}>Place</th>
                <th scope="col" style={{textAlign: "center"}}>Nom</th>
                <th scope="col" style={{textAlign: "center"}}>Victoire</th>
                <th scope="col" style={{textAlign: "center"}}>Ratio</th>
                <th scope="col" style={{textAlign: "center"}}>Points marqués</th>
                <th scope="col" style={{textAlign: "center"}}>Points reçus</th>
            </tr>
            </thead>
            <tbody>
            {rankArray.map((row, idx) => <tr key={idx}>
                <td style={{textAlign: "center"}}>{row.rank}</td>
                <td style={{textAlign: "left"}}>{row.name}</td>
                <td style={{textAlign: "center"}}>{row.win}</td>
                <td style={{textAlign: "center"}}>{row.pointRate.toFixed(3)}</td>
                <td style={{textAlign: "center"}}>{row.pointMake}</td>
                <td style={{textAlign: "center"}}>{row.pointTake}</td>
            </tr>)}
            </tbody>
        </table>
    </>
}

function BuildTree({treeData}) {
    function parseTree(data_in) {
        if (data_in?.data == null)
            return null;

        let node = new TreeNode(data_in.data);
        node.left = parseTree(data_in?.left);
        node.right = parseTree(data_in?.right);

        return node;
    }

    function initTree(data_in) {
        let out = [];
        for (const din of data_in) {
            out.push(parseTree(din));
        }
        return out;
    }

    return <DrawGraph root={initTree(treeData)}/>
}

function PouleResult({data}) {
    const [type, setType] = useState(data.type === 3 ? 1 : data.type)

    useEffect(() => {
        setType(data.type === 3 ? 1 : data.type)
    }, [data]);

    return <>
        {data.type === 3 && <>
            <ul className="nav nav-tabs">
                <li className="nav-item">
                    <a className={"nav-link" + (type === 1 ? " active" : "")} aria-current={(type === 1 ? " page" : "false")} href="#"
                       onClick={_ => setType(1)}>Poule</a>
                </li>
                <li className="nav-item">
                    <a className={"nav-link" + (type === 2 ? " active" : "")} aria-current={(type === 2 ? " page" : "false")} href="#"
                       onClick={_ => setType(2)}>Tournois</a>
                </li>
            </ul>
        </>}

        {type === 1 && <>
            {Object.keys(data.matchs).map(p => <div key={p}>
                {Object.keys(data.matchs).length > 1 && <h4 style={{marginTop: "2em"}}>Poule {p}</h4>}
                <BuildMatchArray matchs={data.matchs[p]}/>
                <BuildRankArray rankArray={data.rankArray[p]}/>
            </div>)}
        </>}

        {type === 2 && <>
            <BuildTree treeData={data.trees}/>
        </>}

    </>
}

function ClubResult({uuid}) {
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/result/${uuid}/club`, setLoading, 1)

    return <>
        {data ? <>
                <h3>Info :</h3>
                <ul>
                    <li>Nom : {data.name}</li>
                    <li>Nombre d'inscris : {data.nb_insc}</li>
                </ul>
                <h3>Statistique :</h3>
                <ul>
                    <li>Nombre de match disput&eacute; : {data.nb_match}</li>
                    <li>Nombre de victoires : {data.match_w}</li>
                    <li>Ratio de victoires moyen : {data.ratioVictoire.toFixed(3)}</li>
                    <li>Points marqués : {data.pointMake}</li>
                    <li>Points reçus : {data.pointTake}</li>
                    <li>Ratio de points moyen : {data.ratioPoint.toFixed(3)}</li>
                </ul>

                <h3>Liste des membres :</h3>

                <table className="table table-striped">
                    <thead>
                    <tr>
                        <th scope="col" style={{textAlign: "center"}}>Cat&eacute;gorie</th>
                        <th scope="col" style={{textAlign: "center"}}>Nom</th>
                        <th scope="col" style={{textAlign: "center"}}>Victoires</th>
                        <th scope="col" style={{textAlign: "center"}}>D&eacute;faites</th>
                        <th scope="col" style={{textAlign: "center"}}>Ratio victoires</th>
                        <th scope="col" style={{textAlign: "center"}}>Points marqués</th>
                        <th scope="col" style={{textAlign: "center"}}>Points reçus</th>
                        <th scope="col" style={{textAlign: "center"}}>Ratio points</th>
                    </tr>
                    </thead>
                    <tbody>
                    {data.combs.map((comb, idx) => <tr key={idx}>
                        <td style={{textAlign: "center"}}>{comb.cat}</td>
                        <td style={{textAlign: "center"}}>{comb.name}</td>
                        <td style={{textAlign: "center"}}>{comb.w}</td>
                        <td style={{textAlign: "center"}}>{comb.l}</td>
                        <td style={{textAlign: "center"}}>{comb.ratioVictoire.toFixed(3)}</td>
                        <td style={{textAlign: "center"}}>{comb.pointMake}</td>
                        <td style={{textAlign: "center"}}>{comb.pointTake}</td>
                        <td style={{textAlign: "center"}}>{comb.ratioPoint.toFixed(3)}</td>
                    </tr>)}
                    </tbody>
                </table>

            </>
            : error
                ? <AxiosError error={error}/>
                : <Def/>
        }
    </>
}

/*function ClubAllResult({uuid}) {
    return <div></div>

}*/

function CombResult({uuid}) {
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/result/${uuid}/comb`, setLoading, 1)

    return <>
        {data ? <>
                <h3>Statistique :</h3>
                <ul>
                    <li>Nombre d'inscris : {data.nb_insc}</li>
                    <li>Nombre de match disput&eacute; : {data.tt_match}</li>
                    <li>Points marqués : {data.point}</li>
                </ul>

                <h3>Liste des combattants :</h3>

                <table className="table table-striped">
                    <thead>
                    <tr>
                        <th scope="col" style={{textAlign: "center"}}>Cat&eacute;gorie</th>
                        <th scope="col" style={{textAlign: "center"}}>Club</th>
                        <th scope="col" style={{textAlign: "center"}}>Nom</th>
                        <th scope="col" style={{textAlign: "center"}}>Victoires</th>
                        <th scope="col" style={{textAlign: "center"}}>D&eacute;faites</th>
                        <th scope="col" style={{textAlign: "center"}}>Ratio victoires</th>
                        <th scope="col" style={{textAlign: "center"}}>Points marqués</th>
                        <th scope="col" style={{textAlign: "center"}}>Points reçus</th>
                        <th scope="col" style={{textAlign: "center"}}>Ratios points</th>
                    </tr>
                    </thead>
                    <tbody>
                    {data.combs.map((comb, idx) => <tr key={idx}>
                        <td style={{textAlign: "center"}}>{comb.cat}</td>
                        <td style={{textAlign: "center"}}>{comb.club}</td>
                        <td style={{textAlign: "center"}}>{comb.name}</td>
                        <td style={{textAlign: "center"}}>{comb.w}</td>
                        <td style={{textAlign: "center"}}>{comb.l}</td>
                        <td style={{textAlign: "center"}}>{comb.ratioVictoire.toFixed(3)}</td>
                        <td style={{textAlign: "center"}}>{comb.pointMake}</td>
                        <td style={{textAlign: "center"}}>{comb.pointTake}</td>
                        <td style={{textAlign: "center"}}>{comb.ratioPoint.toFixed(3)}</td>
                    </tr>)}
                    </tbody>
                </table>
            </>
            : error
                ? <AxiosError error={error}/>
                : <Def/>
        }
    </>
}

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>
}
