<script setup>
import { TabGroup, TabList, Tab, TabPanels, TabPanel} from '@headlessui/vue'
import { KeyIcon, BoltIcon, ShieldCheckIcon, UserPlusIcon, UsersIcon, ClipboardDocumentListIcon} from '@heroicons/vue/24/solid'

import { useAuthStore } from '../../stores/auth';

import Card from '@/components/cards/Card.vue';
import CardHeader from '@/components/cards/CardHeader.vue';
import CardTitle from '@/components/cards/CardTitle.vue';
import CardDescription from '@/components/cards/CardDescription.vue';
import CardContent from '@/components/cards/CardContent.vue';
import Label from '@/components/labels/Label.vue';
import ToogleSwitch from '@/components/buttons/ToogleSwitch.vue';
import { onActivated, onDeactivated, ref } from 'vue';
import InputText from '@/components/inputs/InputText.vue';
import CardFooter from '@/components/cards/CardFooter.vue';
import Button from '@/components/buttons/Button.vue';

import { getSocket } from '@/plugins/socketioManager'
import { io } from 'socket.io-client';

var socket = null
const privateKey = ref("")
const publicKey = ref("")
const proofOfWork = ref("")
const credentialPassword = ref("")
const isLoginEnabled = ref(false)

const lockboxServiceApiUrl = "https://127.0.0.1:5001";
const auth = useAuthStore()

const users = ref({})

function onSwitchChanged(newValue) {
    // privateKeyInput.value = ""
    // privateKeyB64.value = ""
    // publicKeyB64.value = ""
}

function set_login_user(userId){
    if(!isLoginEnabled.value){
        isLoginEnabled.value = true
    }
    publicKey.value = userId
}

function add_user(){
    const data = {password:privateKey.value, data:{proof_of_work:proofOfWork.value}, credentialPassword:credentialPassword.value};
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    };

    fetch(lockboxServiceApiUrl+"/users", requestOptions)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            auth.setToken(data.verifying_key, data.token);
        })
        .catch(error => {
            console.error

        ('Error:', error);
        });
}

function login_user(){
    const data = {credentialPassword:credentialPassword.value};
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    };

    fetch(lockboxServiceApiUrl+"/users/"+publicKey.value+"/login", requestOptions)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            auth.setToken(data.verifying_key, data.token);
        })
        .catch(error => {
            console.error

        ('Error:', error);
        });
}

function logout_user(userId){
    delete auth.tokens[userId]
    list_users()
}

function list_users(){
    fetch(lockboxServiceApiUrl+"/users")
        .then(response => {
            if (!response.ok){
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            users.value = data;
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

function onUserAdded(data){
    console.log(data)
    list_users();
}

onActivated(async () => {
    list_users();

    // const socket = await getSocket("lockbox_lockboxClient")
    socket = io(lockboxServiceApiUrl)
    socket.on('userAdded', onUserAdded);
});

onDeactivated(()=>{
    socket.off('userAdded', onUserAdded);
});

</script>

<template>
    <TabPanel class="flex flex-col space-y-3">
        <Card class="">
            <CardHeader>
                <CardTitle class="flex items-center gap-2 text-yellow-400">
                    <UserPlusIcon class="h-5 w-5" />
                    Add User
                </CardTitle>
                <CardDescription class="text-slate-200">
                    Add a user with private key or login with public key
                </CardDescription>
            </CardHeader>
            <CardContent class=" space-y-2">
                <div class="flex flex-row gap-4">
                    <Label>Add with Private Key</Label>
                    <ToogleSwitch v-model="isLoginEnabled" @update:modelValue="onSwitchChanged"/>
                    <Label>Login with Public Key</Label>
                </div>
                <div v-if="!isLoginEnabled" class="flex flex-col space-y-2 w-full">
                    <Label forId="privateKey" class="text-slate-300">Private Key</Label>
                    <InputText id="privateKey" type="password" v-model="privateKey" placeholder="" class="border-gray-700 bg-slate-300 w-full"/>
                </div>
                <div v-if="!isLoginEnabled" class="flex flex-col space-y-2 w-full">
                    <Label forId="proofOfWork" class="text-slate-300">Proof of Work</Label>
                    <InputText id="proofOfWork" v-model="proofOfWork" placeholder="" class="border-gray-700 bg-slate-300 w-full"/>
                </div>
                <div v-if="isLoginEnabled" class="flex flex-col space-y-2 w-full">
                    <Label forId="publicKey" class="text-slate-300">Public Key</Label>
                    <InputText id="publicKey" v-model="publicKey" placeholder="" class="border-gray-700 bg-slate-300 w-full"/>
                </div>
                <div class="flex flex-col space-y-2 w-full">
                    <Label forId="credentialPassword" class="text-slate-300">Credential Password</Label>
                    <InputText id="credentialPassword" type="password" v-model="credentialPassword" placeholder="" class="border-gray-700 bg-slate-300 w-full"/>
                </div>
            </CardContent>
            <CardFooter>
                <Button v-if="!isLoginEnabled" @click="add_user()" class="flex items-center gap-2 w-full">
                    Save
                </Button>
                <Button v-if="isLoginEnabled" @click="login_user()" class="flex items-center gap-2 w-full">
                    Login
                </Button>
            </CardFooter>
        </Card>

        <Card >
            <CardHeader>
                <CardTitle class="flex items-center gap-2 text-yellow-400">
                    <UsersIcon class="h-5 w-5" />
                    User Management
                </CardTitle>
                <CardDescription class="text-slate-200">
                    View and manage your users in the system
                </CardDescription>
            </CardHeader>
            <div class="px-4">
                <CardContent v-for="user in users" class="border border-yellow-400/20 rounded mb-2 pt-2">
                    <div class="flex flex-row items-start gap-x-5">
                        <div class="space-y-1">
                            <p class="font-mono text-sm text-gray-300">{{user.id}}</p>
                            <div class="flex items-center gap-4 text-sm text-gray-400">
                                <span>Added At: {{user.added_at}}</span>
                            </div>
                        </div>
                        <div class="flex flex-row space-x-3 items-center">
                            <!-- TODO Create field logged:bool -->
                            <div v-if="user.id in auth.tokens">
                                <Button class="bg-red-600" @click="logout_user(user.id)">Logout</Button>
                            </div>
                            <div v-if="!(user.id in auth.tokens)">
                                <Button class="bg-green-600" @click="set_login_user(user.id)">Login</Button>
                            </div>
                        </div>
                    </div>
                </CardContent>
            </div>
        </Card>
    </TabPanel>
</template>