"use client";

import axios from "axios";
import * as React from 'react';
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import GroupElement from "@/components/elements/group";
import RoleGate from "@/components/auth/role-gate";

const permissionPaths = [
    { path: "tts", description: "Anything to do with TTS" },
    { path: "tts.chat", description: "Anything to do with chat" },
    { path: "tts.chat.bits.read", description: "To read chat messages with bits via TTS" },
    { path: "tts.chat.messages.read", description: "To read chat messages via TTS" },
    { path: "tts.chat.redemptions.read", description: "To read channel point redemption messages via TTS" },
    //{ path: "tts.chat.subscriptions.read", description: "To read chat messages from subscriptions via TTS" },
    { path: "tts.commands", description: "To execute commands for TTS" },
    { path: "tts.commands.nightbot", description: "To use !nightbot command" },
    { path: "tts.commands.obs", description: "To use !obs command" },
    { path: "tts.commands.refresh", description: "To use !refresh command" },
    { path: "tts.commands.skip", description: "To use !skip command" },
    { path: "tts.commands.skipall", description: "To use !skipall command" },
    { path: "tts.commands.tts", description: "To use !tts command" },
    { path: "tts.commands.tts.join", description: "To use !tts join command" },
    { path: "tts.commands.tts.leave", description: "To use !tts leave command" },
    { path: "tts.commands.version", description: "To use !version command" },
    { path: "tts.commands.voice", description: "To use !voice command" },
    { path: "tts.commands.voice.admin", description: "To use !voice command on others" },

].sort((a, b) => a.path.localeCompare(b.path))

const GroupPermissionPage = () => {
    const { data: session, status } = useSession();
    const [previousUsername, setPreviousUsername] = useState<string | null>()
    const [groups, setGroups] = useState<{ id: string, name: string, priority: number }[]>([])
    const [permissions, setPermissions] = useState<{ id: string, path: string, allow: boolean | null, groupId: string }[]>([])
    const specialGroups = ["everyone", "subscribers", "vip", "moderators", "broadcaster"]

    function addGroup(id: string, name: string, priority: number) {
        setGroups([...groups, { id, name, priority }])
    }

    function removeGroup(group: { id: string, name: string, priority: number }) {
        setGroups(groups.filter(g => g.id != group.id))
    }

    function containsGroup(groupName: string) {
        return groups.some(g => g.name == groupName)
    }

    useEffect(() => {
        if (status !== "authenticated" || previousUsername == session.user?.name)
            return
        setPreviousUsername(session.user?.name)

        // TODO: fetch groups & permissions
        axios.get('/api/settings/groups')
            .then(d => {
                for (let groupName of specialGroups)
                    if (!d.data.some((g: { id: string, name: string, priority: number }) => g.name == groupName))
                        d.data.push({ id: "$" + groupName, name: groupName, priority: 0 });

                axios.get('/api/settings/groups/permissions')
                    .then(d2 => {
                        setPermissions(d2.data)
                        setGroups(d.data)
                    })
            })
        // TODO: filter permissions by group?

    }, [session])

    return (
        <div>
            <div className="text-2xl text-center pt-[50px]">Groups & Permissions</div>
            {/* <InfoNotice
                message="Redemption actions are activated when specific Twitch channel point redeems have been activated. Aforementioned redeem need to be linked in the redemption part, together with the action, for the action to activate."
                hidden={false} /> */}
            <div className="grid sm:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-3">
            {groups.map(group =>
                <div
                    className="col-span-1"
                    key={group.id}>
                    <GroupElement
                        id={group.id}
                        name={group.name}
                        priority={group.priority}
                        permissionsLoaded={permissions.filter(p => p.groupId == group.id)}
                        edit={group.id.startsWith('$')}
                        showEdit={true}
                        isNewGroup={group.id.startsWith('$')}
                        permissionPaths={permissionPaths}
                        specialGroups={specialGroups}
                        adder={addGroup}
                        remover={removeGroup}
                        contains={containsGroup} />
                </div>
            )}
            <div
                className="col-span-1">
                <GroupElement
                    id={undefined}
                    name={""}
                    priority={0}
                    permissionsLoaded={[]}
                    edit={true}
                    showEdit={false}
                    isNewGroup={true}
                    permissionPaths={permissionPaths}
                    specialGroups={specialGroups}
                    adder={addGroup}
                    remover={removeGroup}
                    contains={containsGroup} />
            </div>
            </div>
        </div>
    );
}

export default GroupPermissionPage;