import React, {useEffect, useRef, useState} from "react";
import {useRequestWS} from "../../../hooks/useWS.jsx";
import {useCombsDispatch} from "../../../hooks/useComb.jsx";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {createPortal} from "react-dom";
import {copyStyles} from "../../../utils/copyStyles.js";
import {PubAffProvider, usePubAffDispatch} from "../../../hooks/useExternalWindow.jsx";
import {faArrowRightArrowLeft, faDisplay} from "@fortawesome/free-solid-svg-icons";
import {PubAffWindow} from "./PubAffWindow.jsx";
import {SimpleIconsScore} from "../../../assets/SimpleIconsScore.ts";
import {ChronoPanel} from "./CMTChronoPanel.jsx";
import {CategorieSelect} from "./CMTMatchPanel.jsx";
import {PointPanel} from "./CMTPoint.jsx";

export function CMTable() {
    const combDispatch = useCombsDispatch()
    const [catId, setCatId] = useState(-1);
    const menuActions = useRef({});
    const {data} = useRequestWS("getRegister", null)

    useEffect(() => {
        if (data === null)
            return;
        combDispatch({type: 'SET_ALL', payload: {source: "register", data: data}});
    }, [data]);

    return <PubAffProvider>
        <div className="text-center">
            <div className="row">
                <div className="col-md-12 col-lg">
                    <div className="card mb-3">
                        <div className="card-header">Chronomètre</div>
                        <div className="card-body">
                            <ChronoPanel/>
                        </div>
                    </div>

                    <div className="card mb-3">
                        <div className="card-header">Score</div>
                        <div className="card-body">
                            <PointPanel menuActions={menuActions}/>
                        </div>
                    </div>
                </div>
                <div className="col-md-12 col-xl-6 col-xxl-5">
                    <div className="card  mb-3">
                        <div className="card-header">Matches</div>
                        <div className="card-body">
                            <CategorieSelect catId={catId} setCatId={setCatId} menuActions={menuActions}/>
                        </div>
                    </div>
                    <div style={{backgroundColor: "#c70000"}}>
                        D
                    </div>
                </div>
            </div>
            <Menu menuActions={menuActions}/>
        </div>
    </PubAffProvider>
}

const windowName = "FFSAFScorePublicWindow";

let tto = [];

function Menu({menuActions}) {
    const e = document.getElementById("actionMenu")
    const publicAffDispatch = usePubAffDispatch()
    const [showPubAff, setShowPubAff] = useState(false)
    const [showScore, setShowScore] = useState(true)

    const externalWindow = useRef(null)
    const containerEl = useRef(document.createElement("div"))

    useEffect(() => {
        if (sessionStorage.getItem(windowName + "_open") === "true") {
            handlePubAff();
        }
        //return () => {
        //    if (!externalWindow.current)
        //        return;
        //    externalWindow.current.close();
        //}
    }, []);

    const handlePubAff = __ => {
        if (showPubAff === false || !externalWindow.current || externalWindow.current.closed) {
            externalWindow.current = window.open("", windowName, "width=800,height=600,left=200,top=200")
            externalWindow.current.document.body.innerHTML = ""
            externalWindow.current.document.body.appendChild(containerEl.current)
            copyStyles(document, externalWindow.current.document)

            externalWindow.current.addEventListener("beforeunload", () => {
                setShowPubAff(false);
                externalWindow.current.close();
                externalWindow.current = null;
                publicAffDispatch({type: 'CLEAR_CB_TIME', payload: null});
                sessionStorage.removeItem(windowName + "_open");
            });
            setShowPubAff(true);
            sessionStorage.setItem(windowName + "_open", "true");
        } else {
            externalWindow.current.focus();
        }
    }

    for (const x of tto)
        x.dispose();
    const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip2"]')
    tto = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))

    const handleScore = __ => {
        setShowScore(!showScore);
        publicAffDispatch({type: 'SET_DATA', payload: {showScore: !showScore}});
    }

    const handleSwitchScore = () => {
        menuActions.current.switchSore?.();
    }

    if (!e)
        return <></>;
    return <>
        {createPortal(
            <>
                <div className="vr" style={{margin: "0 0.5em", height: "100%"}}></div>
                <FontAwesomeIcon icon={faArrowRightArrowLeft} size="xl" style={{color: "#6c757d", cursor: "pointer"}} onClick={handleSwitchScore}
                                 data-bs-toggle="tooltip2" data-bs-placement="top"
                                 data-bs-title="Inverser la position des combattants sur cette écran"/>
                <div className="vr" style={{margin: "0 0.5em", height: "100%"}}></div>
                <FontAwesomeIcon icon={faDisplay} size="xl"
                                 style={{color: showPubAff ? "#00c700" : "#6c757d", cursor: "pointer", marginRight: "0.25em"}}
                                 onClick={handlePubAff}
                                 data-bs-toggle="tooltip2" data-bs-placement="top" data-bs-title="Ouvrir l'affichage public"/>
                <FontAwesomeIcon icon={SimpleIconsScore} size="xl" style={{color: showScore ? "#00c700" : "#6c757d", cursor: "pointer"}}
                                 onClick={handleScore}
                                 data-bs-toggle="tooltip2" data-bs-placement="top" data-bs-title="Afficher les scores sur l'affichage public"/>
            </>, document.getElementById("actionMenu"))}
        {externalWindow.current && createPortal(<PubAffWindow document={externalWindow.current.document}/>, containerEl.current)}
    </>
}
