import React, { useCallback, useEffect, useState } from "react";
import "@fontsource/bungee";
import {
    IconBuildingBroadcastTowerFilled,
    IconHexagonPlusFilled,
    IconClockFilled
} from "@tabler/icons-react";
import { commands, GameSettings, PlayerProfile } from "@/bindings";
import ProfilePicture from "./ProfilePicture";
import LoadingCover from "./LoadingCover";
import { message } from "@tauri-apps/plugin-dialog";

export const defaultSettings: () => GameSettings = () => ({
    random_seed: Math.floor(Math.random() * 2 ** 32),
    hiding_time_seconds: 60 * 5,
    ping_start: "Instant",
    ping_minutes_interval: 10,
    powerup_start: "Instant",
    powerup_chance: 60,
    powerup_minutes_cooldown: 1,
    powerup_locations: []
});

const defaultProfile: PlayerProfile = {
    display_name: "",
    pfp_base64: null
};

export default function MenuScreen() {
    const [profile, setProfile] = useState<PlayerProfile>(defaultProfile);
    const [loadingCover, setLoadingCover] = useState<boolean>(false);

    useEffect(() => {
        let cancel = false;
        commands.getProfile().then((profile) => {
            if (!cancel) {
                setProfile(profile);
            }
        });
        return () => {
            cancel = true;
        };
    }, [setProfile]);

    const startLobby = () => {
        setLoadingCover(true);
        setTimeout(() => {
            commands.startLobby(null, defaultSettings()).catch(() => {
                setLoadingCover(false);
            });
        }, 100);
    };

    const joinLobby = () => {
        setLoadingCover(true);
        const code = window.prompt("Enter join code");
        if (!code) {
            setLoadingCover(false);
            return;
        }
        const cleanedCode = code.toUpperCase().trim();
        commands
            .checkRoomCode(cleanedCode)
            .then((valid) => {
                if (valid) {
                    commands.startLobby(cleanedCode, defaultSettings()).catch(() => {
                        setLoadingCover(false);
                    });
                } else {
                    message("Invalid Join Code", { kind: "error", title: "Failed to Join" });
                    setLoadingCover(false);
                }
            })
            .catch(() => {
                setLoadingCover(false);
            });
    };

    const onEditName = () => {
        const newName = window.prompt("Enter New Name");
        if (!newName) {
            return;
        }

        const newProfile = { ...profile, display_name: newName };
        commands.updateProfile(newProfile);
        setProfile(newProfile);
    };

    const onEditPicture = () => {
        setLoadingCover(true);
        commands
            .createProfilePicture()
            .then((newPic) => {
                if (newPic) {
                    const newProfile = { ...profile, pfp_base64: newPic };
                    commands.updateProfile(newProfile);
                    setProfile(newProfile);
                }
            })
            .finally(() => {
                setLoadingCover(false);
            });
    };

    return (
        <>
            <header>
                <ProfilePicture
                    onClick={onEditPicture}
                    fallbackName={profile.display_name}
                    src={profile.pfp_base64}
                />
                <span className="grow" onClick={onEditName}>
                    Hello,&nbsp;&nbsp;{profile.display_name}
                </span>
            </header>
            <main className="menu">
                <button onClick={startLobby}>
                    <IconBuildingBroadcastTowerFilled size="5em" />
                    Start Lobby
                </button>
                <button onClick={joinLobby}>
                    <IconHexagonPlusFilled size="2.5em" />
                    Join Lobby
                </button>
                <button>
                    <IconClockFilled size="1.5em" />
                    Past Games
                </button>
            </main>
            <LoadingCover show={loadingCover} />
        </>
    );
}
