<template>
    <div>
        <h2>{{ $t('pendingApprovals.title') }}</h2>
        <div v-if="pendingUsers.length > 0">
            <table>
                <thead>
                    <tr>
                        <th>{{ $t('pendingApprovals.firstName') }}</th>
                        <th>{{ $t('pendingApprovals.lastName') }}</th>
                        <th>{{ $t('pendingApprovals.email') }}</th>
                        <th>{{ $t('pendingApprovals.actions') }}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="user in pendingUsers" :key="user.id">
                        <td>{{ user.firstName }}</td>
                        <td>{{ user.lastName }}</td>
                        <td>{{ user.email }}</td>
                        <td>
                            <button @click="approveUser(user.id)">{{ $t('pendingApprovals.approve') }}</button>
                            <button @click="rejectUser(user.id)">{{ $t('pendingApprovals.reject') }}</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div v-else>
            <p>{{ $t('pendingApprovals.noPendingRequests') }}</p>
        </div>
    </div>

    
    <!-- Info Dialog -->
    <InfoDialog
        v-model="infoDialog.isOpen"
        :title="infoDialog.title"
        :message="infoDialog.message"
        :details="infoDialog.details"
        :type="infoDialog.type"
    />
    
    <!-- Confirm Dialog -->
    <ConfirmDialog
        v-model="confirmDialog.isOpen"
        :title="confirmDialog.title"
        :message="confirmDialog.message"
        :details="confirmDialog.details"
        :type="confirmDialog.type"
        @confirm="handleConfirmResult(true)"
        @cancel="handleConfirmResult(false)"
    />
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '../apiClient.js';
import { getSafeErrorMessage } from '../utils/errorMessages.js';

import InfoDialog from '../components/InfoDialog.vue';
import ConfirmDialog from '../components/ConfirmDialog.vue';
export default {
    name: 'PendingApprovalsView',
    data() {
        return {
            // Dialog States
            infoDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info'
            },
            confirmDialog: {
                isOpen: false,
                title: '',
                message: '',
                details: '',
                type: 'info',
                resolveCallback: null
            },
            pendingUsers: [],
        };
    },
    computed: {
        ...mapGetters(['currentClub']),
    },
    async created() {
        await this.loadPendingApprovals();
    },
    methods: {
        // Dialog Helper Methods
        async showInfo(title, message, details = '', type = 'info') {
            this.infoDialog = {
                isOpen: true,
                title,
                message,
                details,
                type
            };
        },
        
        async showConfirm(title, message, details = '', type = 'info') {
            return new Promise((resolve) => {
                this.confirmDialog = {
                    isOpen: true,
                    title,
                    message,
                    details,
                    type,
                    resolveCallback: resolve
                };
            });
        },
        
        handleConfirmResult(confirmed) {
            if (this.confirmDialog.resolveCallback) {
                this.confirmDialog.resolveCallback(confirmed);
                this.confirmDialog.resolveCallback = null;
            }
            this.confirmDialog.isOpen = false;
        },
        
        async loadPendingApprovals() {
            try {
                const response = await apiClient.get(`/clubs/pending/${this.currentClub}`);
                this.pendingUsers = response.data.map(entry => entry.user);
            } catch (error) {
                if (error.response?.status === 403) {
                    await this.showInfo(this.$t('pendingApprovals.noPermission'), this.$t('pendingApprovals.noPermissionMessage'), this.$t('pendingApprovals.noPermissionDetails'), 'error');
                    this.$router.push('/');
                } else {
                    this.showInfo(this.$t('messages.error'), this.$t('pendingApprovals.errorLoadingRequests'), getSafeErrorMessage(error), 'error');
                }
            }
        },
        async approveUser(userId) {
            try {
                await apiClient.post('/clubs/approve', {
                    clubid: this.currentClub,
                    userid: userId,
                });
                this.pendingUsers = this.pendingUsers.filter(user => user.id !== userId);
            } catch (error) {
                this.showInfo(this.$t('messages.error'), this.$t('pendingApprovals.errorApproving'), '', 'error');
            }
        },
        async rejectUser(userId) {
            try {
                await apiClient.post('/clubs/reject', {
                    clubid: this.currentClub,
                    userid: userId,
                });
                this.pendingUsers = this.pendingUsers.filter(user => user.id !== userId);
            } catch (error) {
                this.showInfo(this.$t('messages.error'), this.$t('pendingApprovals.errorRejecting'), '', 'error');
            }
        },
    },
};
</script>

<style scoped>
table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    padding: 10px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

button {
    margin-right: 5px;
    padding: 5px 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}
</style>
