<template>
    <v-container style="overflow: visible!important;">
        <v-row class="pt-16">
            <v-col cols="12">
                <v-card style="overflow: visible !important;" elevation="5">
                    <v-card-title class="d-flex" style="overflow: visible !important;">
                        <v-icon style="position:relative; top:-30px; overflow: visible !important;" class="mdi-with-border" color="white">mdi-shield-account</v-icon>
                        <h3 class="pl-5" style="color:#565656">Administrators Manager</h3>
                        <v-spacer></v-spacer>
                        <v-btn color="success" prepend-icon="mdi-plus" variant="text" @click="newAdminDrawer=true">CREATE</v-btn>
                    </v-card-title>
                    <v-card-text>
                        <!--<v-row>
                            <v-col cols="2">
                                <v-text-field density="compact" variant="underlined" label="Search" append-inner-icon="mdi-magnify" single-line hide-details></v-text-field>
                            </v-col>
                            <v-spacer></v-spacer>
                            <v-col cols="5" class="d-flex flex-row-reverse">
                                <v-btn color="success" prepend-icon="mdi-plus" variant="text" @click="newAdminDrawer=true">CREATE</v-btn>
                                <v-btn color="success" prepend-icon="mdi-filter-variant-plus" variant="text">ADD FILTER</v-btn>
                            </v-col>
                        </v-row>-->

                        <v-row>
                            <v-col cols="12">
                                <v-data-table :headers="headers" :items="admins" :loading="loadingAdmins">
                                    <template v-slot:item.actions="{ item }">
                                        <!--<v-btn icon="$vuetify" variant="text" color="green-accent-3">
                                            <v-tooltip activator="parent" location="bottom">
                                                View
                                            </v-tooltip>
                                           <v-icon size="large" style="cursor: pointer;" icon="mdi-eye"></v-icon>
                                        </v-btn>-->

                                        <v-btn icon="$vuetify" variant="text" color="orange-accent-3" @click="openEditDrawer(item.id)">
                                            <v-tooltip activator="parent" location="bottom">
                                                Edit
                                            </v-tooltip>
                                            <v-icon size="large" style="cursor: pointer;" icon="mdi-pencil"></v-icon>
                                        </v-btn>

                                        <v-btn icon="$vuetify" variant="text" color="red-accent-3" @click="showDeleteDialog(item.id, item.name);">
                                            <v-tooltip activator="parent" location="bottom">
                                                Delete
                                            </v-tooltip>
                                            <v-icon size="large" style="cursor: pointer;" icon="mdi-trash-can"></v-icon>
                                        </v-btn>
                                    </template>
                                </v-data-table>
                            </v-col>
                        </v-row>
                    </v-card-text>

                </v-card>
            </v-col>
            
        </v-row>

        <v-navigation-drawer temporary location="right" v-model="newAdminDrawer" elevation="5" rail rail-width="600">
            <v-row justify="end" style="padding-top: 20px;padding-right: 20px;"><v-hover v-slot="{ isHovering, props }"><v-icon size="small" v-bind="props" :color="isHovering ? 'grey-darken-1' : 'grey-lighten-1'" variant="plain" icon="mdi-close" @click="closeDrawers()"></v-icon></v-hover></v-row>
            <v-row class="d-flex pb-8">
                <v-col align="center" cols="12" class="pb-0">
                    <v-avatar color="green-lighten-1" size="80">
                        <v-icon size="50" icon="mdi-account-plus"></v-icon>
                    </v-avatar>
                </v-col>
                <v-col align="center" cols="12" style="font-size: 25px;color:#66BB6A" class="pt-0 mt-0"><strong>New Administrator</strong></v-col>
            </v-row>

            <v-form ref="form" lazy-validation>
                <v-row v-if="!newAdminStore && newAdminStored == 0" class="d-flex pb-8 px-5">
                    <v-col cols="12" class="py-0">
                        <v-text-field v-model="newAdminFirstname" label="Firstname" :rules="validationRules.firstname" required :error="isError('newAdminFirstname')" :error-messages="isErrorMessage('newAdminFirstname')"></v-text-field>
                    </v-col>
                    <v-col cols="12" class="py-0">
                        <v-text-field v-model="newAdminLastname" label="Lastname" :rules="validationRules.lastname" required :error="isError('newAdminLastname')" :error-messages="isErrorMessage('newAdminLastname')"></v-text-field>
                    </v-col>
                    <v-col cols="12" class="py-0">
                        <v-text-field v-model="newAdminEmail" label="Email"  :rules="validationRules.email" required :error="isError('newAdminnewAdminEmailFirstname')" :error-messages="isErrorMessage('newAdminEmail')"></v-text-field>
                    </v-col>
                    <v-col cols="12" class="pb-0 pt-10">
                        <v-text-field v-model="newAdminPassword" label="Password" :rules="validationRules.password" required :error="isError('newAdminPassword')" :error-messages="isErrorMessage('newAdminPassword')"></v-text-field>
                    </v-col>

                    <v-col cols="12" class="pb-0 pt-10">
                        <v-select label="Admin role" v-model="newAdmindRole" :items="adminRoles" item-title="name" item-value="id" variant="solo-filled" :rules="validationRules.role" required :error="isError('newAdmindRole')" :error-messages="isErrorMessage('newAdmindRole')"></v-select>
                    </v-col>
                </v-row>
            </v-form>

            <v-row v-if="!newAdminStore && newAdminStored == 0" class="d-flex pb-8 pl-5">
                <v-col cols="12">
                    <v-btn prepend-icon="mdi-floppy" variant="tonal" color="success" @click="submitForm">Save</v-btn>
                </v-col>
            </v-row>

            <v-row v-if="newAdminStore && newAdminDrawer" class="d-flex pb-8 pl-0" style="z-index: 99998!important;">
                <v-col cols="12">
                    <dotlottie-player src="/images/live/Animation - 1708971320965.json" :autoplay="true" :loop="true" style="width: 320px; margin: auto;"/>
                </v-col>
            </v-row>

            <v-row v-if="newAdminStored == 1 && newAdminDrawer" class="d-flex pb-8 pl-0" style="z-index: 99998!important;">
                <dotlottie-player src="/images/live/Animation - 1708970904056.json" :autoplay="true" :loop="true" :speed="2" style="width: 320px; margin: auto;" @loop="newAdminStored=0;newAdminDrawer = false;loadAdmins()"/>
            </v-row>

            <v-row v-if="newAdminStored == 2 && newAdminDrawer" class="d-flex pb-8 pl-0" style="z-index: 99998!important;">
                <dotlottie-player src="/images/live/Animation - 1708971193718.json" :autoplay="true" :loop="true" style="width: 320px; margin: auto;" @loop="newAdminStored=0;"/>
            </v-row>
        </v-navigation-drawer>

        <v-navigation-drawer temporary location="right" v-model="editAdminDrawer" elevation="5" rail rail-width="600">
            <v-row justify="end" style="padding-top: 20px;padding-right: 20px;"><v-hover v-slot="{ isHovering, props }"><v-icon size="small" v-bind="props" :color="isHovering ? 'grey-darken-1' : 'grey-lighten-1'" variant="plain" icon="mdi-close" @click="closeDrawers()"></v-icon></v-hover></v-row>
            <v-row class="d-flex pb-8">
                <v-col align="center" cols="12" class="pb-0">
                    <v-avatar color="green-lighten-1" size="80">
                        <v-icon size="50" icon="mdi-account-edit"></v-icon>
                    </v-avatar>
                </v-col>
                <v-col align="center" cols="12" style="font-size: 25px;color:#66BB6A" class="pt-0 mt-0"><strong>Edit Administrator</strong></v-col>
            </v-row>

            <v-form ref="editForm" lazy-validation>
                <v-row v-if="!newAdminStore && newAdminStored == 0" class="d-flex pb-8 px-5">
                    <v-col cols="12" class="py-0">
                        <v-text-field v-model="newAdminFirstname" label="Firstname" :rules="validationRules.firstname" required :error="isError('newAdminFirstname')" :error-messages="isErrorMessage('newAdminFirstname')"></v-text-field>
                    </v-col>
                    <v-col cols="12" class="py-0">
                        <v-text-field v-model="newAdminLastname" label="Lastname" :rules="validationRules.lastname" required :error="isError('newAdminLastname')" :error-messages="isErrorMessage('newAdminLastname')"></v-text-field>
                    </v-col>
                    <v-col cols="12" class="py-0">
                        <v-text-field v-model="newAdminEmail" label="Email"  :rules="validationRules.email" required :error="isError('newAdminnewAdminEmailFirstname')" :error-messages="isErrorMessage('newAdminEmail')"></v-text-field>
                    </v-col>
                    <v-col cols="12" class="pb-0 pt-10">
                        <v-text-field v-model="newAdminPassword" label="Password" :error="isError('newAdminPassword')" :error-messages="isErrorMessage('newAdminPassword')"></v-text-field>
                    </v-col>

                    <v-col cols="12" class="pb-0 pt-10">
                        <v-select label="Admin role" v-model="newAdmindRole" :items="adminRoles" item-title="name" item-value="id" variant="solo-filled" :rules="validationRules.role" required :error="isError('newAdmindRole')" :error-messages="isErrorMessage('newAdmindRole')"></v-select>
                    </v-col>
                </v-row>
            </v-form>

            <v-row v-if="!newAdminStore && newAdminStored == 0" class="d-flex pb-8 pl-5">
                <v-col cols="12">
                    <v-btn prepend-icon="mdi-floppy" variant="tonal" color="success" @click="submitEditForm()">Save</v-btn>
                </v-col>
            </v-row>

            <v-row v-if="newAdminStore && editAdminDrawer" class="d-flex pb-8 pl-0" style="z-index: 99998!important;">
                <v-col cols="12">
                    <dotlottie-player src="/images/live/Animation - 1708971320965.json" :autoplay="true" :loop="true" style="width: 320px; margin: auto;"/>
                </v-col>
            </v-row>

            <v-row v-if="newAdminStored == 1 && editAdminDrawer" class="d-flex pb-8 pl-0" style="z-index: 99998!important;">
                <dotlottie-player src="/images/live/Animation - 1708970904056.json" :autoplay="true" :loop="true" :speed="2" style="width: 320px; margin: auto;" @loop="newAdminStored=0;editAdminDrawer = false;loadAdmins()"/>
            </v-row>

            <v-row v-if="newAdminStored == 2 && editAdminDrawer" class="d-flex pb-8 pl-0" style="z-index: 99998!important;">
                <dotlottie-player src="/images/live/Animation - 1708971193718.json" :autoplay="true" :loop="true" style="width: 320px; margin: auto;" @loop="newAdminStored=0;"/>
            </v-row>
        </v-navigation-drawer>

        <v-dialog v-model="deleteAdmindialog" width="auto" persistent @keydown.esc="cancel">
            <v-card min-width="50vh" min-height="22vh">
                <v-card-title>
                    <v-row justify="end" class="pt-2"><v-hover v-slot="{ isHovering, props }"><v-icon size="small" v-bind="props" :color="isHovering ? 'grey-darken-1' : 'grey-lighten-1'" variant="plain" icon="mdi-close" @click.native="cancel"></v-icon></v-hover></v-row>
                </v-card-title>

                <v-card-text v-if="!deleteAdminLoading && deleteAdminstatus === null">
                    <v-row class="d-flex">
                        <v-col align="center" cols="12">
                            <v-avatar color="red-lighten-1" size="80">
                                <v-icon size="50" icon="mdi-account-remove"></v-icon>
                            </v-avatar>
                        </v-col>
                        <v-col align="center" cols="12" style="font-size: 16px;color:#EF5350"><strong>{{ message }}</strong></v-col>
                    </v-row> 
                </v-card-text>
                <v-card-text v-if="deleteAdminLoading">
                    <v-row class="d-flex" style="z-index: 99998!important;">
                        <v-col cols="12">
                            <dotlottie-player src="/images/live/Animation - 1708971320965.json" :autoplay="true" :loop="true" style="width: 320px; margin: auto;"/>
                        </v-col>
                    </v-row>
                </v-card-text>
                <v-card-text v-if="!deleteAdminLoading && deleteAdminstatus == 'Success'">
                    <v-row class="d-flex" style="z-index: 99998!important;">
                        <v-col cols="12" class="pb-0 mb-0">
                            <dotlottie-player src="/images/live/Animation - 1709054852556.json" :autoplay="true" :count="1" style="width: 150px; margin: auto;"/>
                        </v-col>
                        <v-col cols="12" align="center" class="pt-0 mt-0">
                            <h3 style="color:#66BB6A">Administrator deleted successfully</h3>
                        </v-col>
                    </v-row>
                </v-card-text>
                <v-card-text v-if="!deleteAdminLoading && deleteAdminstatus == 'Error'">
                    <v-row class="d-flex" style="z-index: 99998!important;">
                        <v-col cols="12" class="pb-0 mb-0">
                            <dotlottie-player src="/images/live/Animation - 1709054705289.json" :autoplay="true" :count="1" style="width: 150px; margin: auto;"/>
                        </v-col>
                        <v-col cols="12" align="center" class="pt-0 mt-0">
                            <h3 style="color:#EF5350">{{ deleteAdminMessage }}</h3>
                        </v-col>
                    </v-row>
                </v-card-text>
                <v-card-actions class="pt-3">
                    <v-btn v-if="!deleteAdminLoading && deleteAdminstatus === null" color="green-darken-1" text @click.native="agree">Yes</v-btn>
                    <v-spacer></v-spacer>
                    <v-btn v-if="!deleteAdminLoading && deleteAdminstatus === null" color="red-darken-1" text @click.native="cancel">No</v-btn>
                    <v-btn v-if="!deleteAdminLoading && deleteAdminstatus" color="grey-darken-1" text @click.native="cancel">Close</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        
        
        
   </v-container>
</template>
<style>
.mdi-with-border {
  border: 2px solid #8EBE20; /* Set your border color */
  border-radius: 10%; /* Optional: Make it circular */
  background-color: #8EBE20; /* Set your background color */
  padding: 50px; /* Optional: Adjust padding as needed */
  font-size: 80px; /* Optional: Adjust font size */
  color: #ffffff; /* Optional: Set icon color */
}
</style>
<script>
export default {

  components: {
  },

  data: () => ({
    breadcrumbs: [
        { title: "Home", disabled: false, href: "/" },
        { title: "Admin Manager", disabled: true },
    ],

    headers: [
        { key: 'name',title: 'Name'},
        { key: 'email', title: 'Email' },
        { key: 'role', title: 'Role' },
        { key: 'created', title: 'Created at' },
        { key: 'updated', title: 'Updated at' },
        { key: 'actions', title: ''},
    ],

    adminRoles:[
        {id:1, name:"Full Administrator"},
        {id:2, name:"Intenal IT"},
        {id:3, name:"Moderator"},
    ],

    loadingAdmins:false,
    admins:[],

    validationRules:{
        firstname: [
            v => !!v || 'Firstname is required',],
        lastname: [
            v => !!v || 'Lastname is required',],
        email:[
            v => !!v || 'Email is required',
            v => /^(([^<>()[\]\\.,;:\s@']+(\.[^<>()\\[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(v) || 'E-mail must be valid',],
        password:[
            v => !!v || 'Password is required',
            v => /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/.test(v) || 'Password must contain at least one lowercase letter, one number, a special character and one uppercase letter',],
        role:[
        v => !!v || 'Admin role is required',
        ],
    },

    deleteAdmindialog:false,
    deleteAdminLoading:false,
    deleteAdminstatus:null,
    deleteAdminMessage:null,
    resolve: null,
    reject: null,
    message: null,
    title: null,

    editAdminDrawer:false,
    newAdminDrawer:false,
    adminID: 0,
    newAdminStore:false,
    newAdminStored:0,
    errors:{},
    errorsMessages:{},
    newAdminFirstname:'',
    newAdminLastname:'',
    newAdminEmail:'',
    newAdminPassword:'',
    newAdminPasswordConfirm:'',
    newAdmindRole:'',
  }),

  watch: {
        newAdminDrawer(newValue, oldValue) {
            if (!newValue) {
                this.closeDrawers();
            }
        },
        editAdminDrawer(newValue, oldValue) {
            if (!newValue) {
                this.closeDrawers();
            }
        },
    },

  mounted() {
    this.loadAdmins();
  },
 
  methods: {
    closeDrawers() {
        this.adminID = 0;
        this.newAdminDrawer = false;
        this.editAdminDrawer = false;
        this.newAdminFirstname = '';
        this.newAdminLastname = '';
        this.newAdminEmail = '';
        this.newAdminPassword = '';
        this.newAdminPasswordConfirm = '';
        this.newAdmindRole = '';
        this.errors = {};
        this.errorsMessages = {};
        this.$refs.form.reset();
        this.$refs.editForm.reset();
    },

    openEditDrawer(adminID) {
        this.editAdminDrawer = true;
        this.admins.forEach((el, index) => {
            if (parseInt(el.id) === parseInt(adminID)) {
                this.newAdminFirstname = el.firstname;
                this.newAdminLastname = el.lastname;
                this.newAdminEmail = el.email;
                this.newAdmindRole = el.roleID;
                this.adminID = el.id;
            }
        });
    },

    loadAdmins() {
        this.loadingAdmins = true;
        this.$root.axiosGet('/admin-manager/load').then(data => {
            this.loadingAdmins = false;
            this.admins = data.response.data.data;
        }); 
    },

    async showDeleteDialog(ID,name) {
        this.deleteAdminstatus = null;
        this.deleteAdminMessage = null;  
        if (await this.open("Confirm","Are you sure you want to delete administrator: #"+ID+' '+name+'?')) {
            this.deleteAdmin(ID);
        }
    },

    open(title, message, options) {
        this.deleteAdmindialog = true;
        this.title = title;
        this.message = message;
        return new Promise((resolve, reject) => {
            this.resolve = resolve;
            this.reject = reject;
        });
    },

    agree() {
        this.resolve(true);
    },

    cancel() {
        this.resolve(false);
        this.deleteAdmindialog = false;
    },

    async deleteAdmin(ID) {
        let response;
        this.deleteAdminLoading = true;
        this.$root.axiosPost('/admin-manager/delete/'+ID, null, {}, false).then(data => {
            this.deleteAdminLoading = false;
            response = data.response.data;
            console.log(response)
            this.deleteAdminstatus = response.status;
            this.deleteAdminMessage = response.message;
            this.loadAdmins();          
        });
    },

    async submitEditForm() {
        const formValid = await this.$refs.editForm.validate();
        if (formValid.valid) {
            this.$root.$refs.globaloverlayemp.showOverlay(true);
            this.newAdminStore = true;
            this.errors = {};
            this.errorsMessages = {};
            let response;
            let params = {
                newAdminFirstname: this.newAdminFirstname,
                newAdminLastname: this.newAdminLastname,
                newAdminEmail: this.newAdminEmail,
                newAdminPassword: this.newAdminPassword,
                newAdmindRole: this.newAdmindRole
            };

            this.$root.axiosPost('/admin-manager/edit/'+this.adminID, null, params, false).then(data => {
                response = data.response.data;
                this.$root.$refs.globaloverlayemp.showOverlay(false);
                this.newAdminStore = false;
                if (response.status === 'Error') {
                    this.newAdminStored = 2;
                    if (response.message === 'Validation Error.') {
                        response.data.forEach((el, index) => {
                            Object.entries(el).forEach((el1, index1) => {
                                this.errors[el1[0]] = !this.isError(el1[0]);
                                this.errorsMessages[el1[0]] = el1[1];
                            });
                        });
                    } else {
                        this.$root.$refs.snackbar.showMessage(response.message, response.status);
                    }
                    
                } else {
                    this.newAdminStored = 1;
                }
            });
        }
    },

    async submitForm () {
        const formValid = await this.$refs.form.validate();
        if (formValid.valid) {
            this.$root.$refs.globaloverlayemp.showOverlay(true);
            this.newAdminStore = true;
            this.errors = {};
            this.errorsMessages = {};
            let response;
            let params = {
                newAdminFirstname: this.newAdminFirstname,
                newAdminLastname: this.newAdminLastname,
                newAdminEmail: this.newAdminEmail,
                newAdminPassword: this.newAdminPassword,
                newAdmindRole: this.newAdmindRole
            };

            this.$root.axiosPost('/admin-manager/new', null, params, false).then(data => {
                response = data.response.data;
                this.$root.$refs.globaloverlayemp.showOverlay(false);
                this.newAdminStore = false;
                if (response.status === 'Error') {
                    this.newAdminStored = 2;
                    if (response.message === 'Validation Error.') {
                        response.data.forEach((el, index) => {
                            Object.entries(el).forEach((el1, index1) => {
                                this.errors[el1[0]] = !this.isError(el1[0]);
                                this.errorsMessages[el1[0]] = el1[1];
                            });
                        });
                    } else {
                        this.$root.$refs.snackbar.showMessage(response.message, response.status);
                    }
                } else {
                    this.newAdminStored = 1;
                }
            });
        }
    },

    isError(fieldName) {
        return this.errors[fieldName];
    },

    isErrorMessage(fieldName) {
        return this.errorsMessages[fieldName];
    },

  }
}
</script>

