import { useRef } from "preact/hooks";
import PeopleView from "./peopleViews/PeopleView";
import PersonView from "./peopleViews/PersonView";
import Button from "../miniComponents/Button";

export default function ({
    roomName,
    people,
    staff,
    messageHistory,
    user,
    setUser,
    currentPeopleView,
    setCurrentPeopleView
}) {
    const peopleBarRef = useRef<HTMLDivElement>();

    const peopleViews = {
        people: <PeopleView  setUser={setUser} staff={staff} setCurrentPeopleView={setCurrentPeopleView} roomName={roomName} people={people}></PeopleView>,
        person: <PersonView user={user}></PersonView>
    }

    return <>
        <div id="peopleBar" class="bg-slate-300  w-52 overflow-auto flex flex-col break-all" style="display:none;" ref={peopleBarRef}>
            {
                (() => {
                    const sidebar = peopleViews[currentPeopleView];
                    return sidebar;
                })()
            }

            {
                (() => {
                    const e = <Button extraClass="mt-auto" onClick={() => {
                        console.log(messageHistory)
                        const blob = new Blob([JSON.stringify(messageHistory)], {type: "application/json"})
                        const elem = window.document.createElement('a');
                        elem.href = window.URL.createObjectURL(blob);
                        elem.download = `${new Date().toUTCString()} trillium logs.json`;        
                        document.body.appendChild(elem);
                        elem.click();        
                        document.body.removeChild(elem);
                    }}>Export logs</Button>
    
                    if (!staff) return e;
                    if (currentPeopleView == "person") {
                        return <Button extraClass="mt-auto" onClick={
                            () => {
                                setCurrentPeopleView("people");
                            }
                        } >
                            View people
                        </Button>
                    } else if (currentPeopleView == "people") {
                        return e;
                    }
                })()
            }
        </div>

        <button class="absolute top-4 right-6" id="peopleBarButton" onClick={
            (e) => {
                const tt = (e.target as HTMLDivElement).parentElement;
                if (peopleBarRef.current.style.display != "none") {
                    tt.className = tt.className.replace("right-64", 'right-6')
                    peopleBarRef.current.style.display = "none"
                } else {
                    tt.className = tt.className.replace('right-6', "right-64")

                    peopleBarRef.current.style.display = "flex";
                }
            }
        }>
            <i class="fa-solid fa-ellipsis text-5xl text-black "></i>
        </button></>;
}