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

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 { onActivated, onDeactivated, ref } from 'vue';
import Button from '@/components/buttons/Button.vue';

import { useAuthStore } from '../../stores/auth';
import { io } from 'socket.io-client';

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

const requestedSignatures = ref([])

async function listSignatureRequests(user){
    const requestOptions = {
        method: 'GET',
        headers: {'Authorization': 'Bearer ' + auth.tokens[user]}
    };
    fetch(lockboxServiceApiUrl+"/users/"+user+"/signatures", requestOptions)
        .then(response => {
            if (!response.ok){
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            requestedSignatures.value = data
        })
        .catch(error => {
            console.error('Error:', error); 
    });
}

function approveSignature(requestId, user, approved){
    const data = {"approved":approved};
    const requestOptions = {
        method: 'POST',
        headers: {'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + auth.tokens[user]},
        body: JSON.stringify(data),
    };

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

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

function onUserAdded(data){
    console.log(data)
    updateSignatures()
}

function onSignatureWaiting(data){
    console.log(data)
    updateSignatures()
}

onActivated(async () => {
    // const socket = await getSocket("lockbox_lockboxClient")
    socket = io(lockboxServiceApiUrl)
    socket.on('userAdded', onUserAdded);
    socket.on('signatureWaiting', onSignatureWaiting);
    updateSignatures();
});

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

function updateSignatures(){
    Object.entries(auth.tokens).forEach(([key, token]) => {
        listSignatureRequests(key)
    })
}
</script>

<template>
    <TabPanel>
        <!-- Head -->
        <Card >
            <CardHeader>
                <CardTitle class="flex items-center gap-2 text-yellow-400">
                    <ClipboardDocumentListIcon class="h-5 w-5" />
                    Pending Signing Requests
                </CardTitle>
                <CardDescription class="text-slate-200">
                    Review and approve signing requests from logged-in users
                </CardDescription>
            </CardHeader>

            <CardContent>
                <CardContent v-for="request in requestedSignatures" class="border border-slate-300 rounded mb-2 pt-2">
                    <div class="flex flex-row space-x-5">
                        <div class="flex flex-col w-full">
                            <p class="font-mono text-sm text-gray-300">{{request.publicKey}}</p>
                            <p class="font-mono text-sm text-gray-300">{{request.requestId}}</p>
                            <p class="font-mono text-sm text-gray-300">{{request.info}}</p>
                            <div class="flex items-center gap-4 text-sm text-gray-400">
                                <span>{{request.data}}</span>
                            </div>
                        </div>
                        <div class="flex flex-col space-x-3 items-center">
                            <p class="font-mono text-sm text-gray-300">{{request.action}}</p>
                            <div class="flex flex-row gap-2">
                                <Button class="bg-green-600" @click="approveSignature(request.requestId, request.user, true)">Approve</Button>
                                <Button class="bg-red-600" @click="approveSignature(request.requestId, request.user, false)">Reject</Button>
                            </div>
                        </div>
                    </div>
                </CardContent>
            </CardContent>
        </Card>
        
    </TabPanel>
</template>