import lobbystyles from "@/styles/lobby.module.css";
import Participants from "@/components/Lobby/Participants";
import SettingsPanel from "@/components/Lobby/SettingsPanel";
import Button from "@/components/Button";
import type { AppUser } from "@/types/lobby";
import { useRouter } from "next/router";
import { useEffect, useState, useContext, useRef } from "react";
import { SessionHandlerContext } from "./Session";
import { useSession } from "next-auth/react";
import { SessionState, UserState, WsEvent } from "@/lib/SessionData/Enums";
import { Settings as SessionSettings, Update, User as WsUser } from "@/lib/SessionData/Interfaces";

function Lobby({ sessionCode }: { sessionCode: string }) {

    const [copyMessage, setCopyMessage] = useState<string | null>(null);
    const router = useRouter();
    const { data: session } = useSession();
    const code = sessionCode;
    const user = (session?.user as AppUser | undefined) ?? null;

    const [settings, setSettings] = useState<SessionSettings | null>(null);
    const [wsUsers, setWsUsers] = useState<Array<WsUser>>([]);
    const [isAdmin, setIsAdmin] = useState<boolean | null>(null);
    const [currentClientId, setCurrentClientId] = useState<string | null>(null);

    const wasPresentRef = useRef(false);

    const sessionHandler = useContext(SessionHandlerContext);

    // Session Handler wird initialisiert und stellt Verbindung her
    useEffect(() => {
        if (!sessionHandler) return;

        // Beim init die aktuellen Werte holen
        setWsUsers(sessionHandler.userHandler?.getUsers() ?? []);
        setSettings(sessionHandler.lobbyHandler?.getSettings() ?? null);

        sessionHandler.userHandler?.onChange((users) => {
            setWsUsers(users);
        });

        sessionHandler.lobbyHandler?.onChange((settings) => {
            console.log("Lobby settings updated:", settings);
            setSettings(settings);
        });

    }, [sessionHandler]);


    useEffect(() => {
        const sessionUserId = user?.id ? Number(user.id) : null;
        const match = wsUsers.find((u) =>
            sessionUserId !== null ? u.userId === sessionUserId : u.id === currentClientId
        );
        setIsAdmin(match?.isAdmin ?? false);
    }, [user, wsUsers, currentClientId]);

    useEffect(() => {
        if (!sessionHandler) return;
        const socketId = sessionHandler.getClientId();
        if (socketId && socketId !== currentClientId) {
            setCurrentClientId(socketId);
        }
    }, [sessionHandler, currentClientId]);

    useEffect(() => {
        if (!currentClientId) return;
        if (wsUsers.some((u) => u.id === currentClientId)) {
            wasPresentRef.current = true;
            return;
        }
        if (wasPresentRef.current) {
            router.push("/");
        }
    }, [wsUsers, currentClientId, router]);

    const startDrawingSession = async () => {
        if (!sessionHandler) return;
        if (sessionHandler.sessionState !== SessionState.Lobby) return;

        sessionHandler.lobbyHandler?.startDrawingSession();
    }

    async function handleCopyCode() {
        if (!sessionCode) return;
        try {
            await navigator.clipboard.writeText(sessionCode);
            setCopyMessage("Code kopiert!");
            setTimeout(() => setCopyMessage(null), 2000);
        } catch {
            setCopyMessage("Kopieren fehlgeschlagen");
            setTimeout(() => setCopyMessage(null), 2000);
        }
    }



    const copyLabel = copyMessage ?? ("Session-Code kopieren");
    const CopyIcon = (
        <svg
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            aria-hidden="true"
        >
            <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
        </svg>
    );

    return (
        <div className={lobbystyles.page}>

            <h1 className={lobbystyles.heading}>Session-Einstellungen</h1>
            <div className={lobbystyles.lobbyContainer}>
                <div className={lobbystyles.leftColumn}>
                    <div className={lobbystyles.participantsColumn}>
                        <Participants
                            seatCount={settings?.maxPlayers ?? wsUsers.length ?? 0}
                            participants={wsUsers}
                            currentClientId={currentClientId}
                            onKick={(p) => {
                                sessionHandler?.userHandler?.kickUser(p.id);
                            }}
                            canKick={isAdmin === true}
                            onRename={(participant, newName) => {
                                sessionHandler?.sendEvent({
                                    event: WsEvent.UserUpdate,
                                    data: { type: UserState.Update, value: { ...participant, name: newName } } as Update,
                                    message: null,
                                    error: null,
                                });
                            }}
                        />
                        <Button
                            variant="primary"
                            className={lobbystyles.copyButton}
                            onClick={handleCopyCode}
                            disabled={!code}
                            icon={CopyIcon}
                        >
                            {copyLabel}
                        </Button>
                    </div>
                </div>

                <div className={lobbystyles.rightColumn}>
                    {settings && <SettingsPanel settings={settings} canEdit={isAdmin === true} />}

                    {isAdmin && (
                        <div className={lobbystyles.startButtonRow}>
                            <Button variant="primary" onClick={startDrawingSession}>
                                Session starten
                            </Button>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

export default Lobby;
