<template>
    <v-app-bar color="primary" prominent app>
    <v-app-bar-nav-icon variant="text" @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
    <v-toolbar-title>Menu</v-toolbar-title>
    <v-spacer></v-spacer>
    <v-btn 
      v-if="!isAuthenticated" 
      prepend-icon="mdi-login" 
      variant="text"
      @click="navigate('/autenticarse')"
    >
      Login
    </v-btn>
    <v-btn 
      v-else 
      variant="text"
    >
      <v-menu activator="parent">
        <v-list>
          <v-list-item>
            <v-list-item-title class="font-weight-bold">{{ user?.username }}</v-list-item-title>
            <v-list-item-subtitle>{{ user?.email }}</v-list-item-subtitle>
          </v-list-item>
          <v-divider></v-divider>
          <v-list-item v-if="user?.first_name || user?.last_name">
            <v-list-item-title>{{ user?.first_name }} {{ user?.last_name }}</v-list-item-title>
          </v-list-item>
          <v-list-item>
            <v-chip 
              :color="user?.role === 'administrator' ? 'error' : 'primary'" 
              size="small"
            >
              {{ user?.role === 'administrator' ? 'Administrador' : 'Usuario' }}
            </v-chip>
          </v-list-item>
          <v-divider></v-divider>
          <v-list-item @click="logout">
            <v-list-item-title>
              <v-icon start>mdi-logout</v-icon>
              Cerrar sesión
            </v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>
      <v-icon start>mdi-account</v-icon>
      {{ user?.username }}
    </v-btn>
  </v-app-bar>
  <v-navigation-drawer v-model="drawer"
                       :location="$vuetify.display.mobile ? 'bottom' : undefined"
                       temporary>
    <v-list
      density="compact"
      nav
    >
      <v-list-item
        v-for="item in filteredMenuItems"
        :key="item.title"
        :title="item.title"
        :prepend-icon="item.icon"
        @click="navigate(item.route)"
      ></v-list-item>
      <v-list-item prepend-icon="mdi-cog" title="Administracion" @click="toggleAdminMenu()" v-if="isAuthenticated && isAdmin"></v-list-item>
      <v-list-item v-if="isAuthenticated && isAdmin && showAdminMenu">
        <v-list>
          <template v-for="(item, index) in menuAdminItems" :key="index">
            <v-divider v-if="item.divider"></v-divider>
            <v-list-subheader v-else-if="item.header">{{ item.header }}</v-list-subheader>
            <v-list-item
              v-else
              :title="item.title"
              :prepend-icon="item.icon"
              @click="navigateAdmin(item.route)"
            ></v-list-item>
          </template>
        </v-list>
      </v-list-item>
    </v-list>
  </v-navigation-drawer>
</template>

<script>
 import AuthService from '@/services/auth';
 import { useAuthStore } from '@/stores/auth';
 import { inject } from 'vue';
 export default {
     name: 'NavBar',
     setup() {
       const authStore = useAuthStore();
       return { authStore };
     },
     data: () => ({
         drawer: false,
         group: null,
         showAdminMenu: false,
         isAuthenticated: false,
         user: null,
         api: inject('api'),
        menuItems: [
            { title: 'Inicio', route: '/', icon: 'mdi-home'},
            { title: 'Comprar', route:'/comprar', icon: 'mdi-cart'},
            { title: 'Ver Catálogo', route: '/catalog', icon: 'mdi-store'},
        ],
         menuAdminItems: [
             { title: 'Cuadrar tarro', route: '/cuadrar_tarro', icon: 'mdi-calculator'},
             { title: 'Cuadres de tarro', route: '/cuadres_de_tarro', icon: 'mdi-chart-bar'},
             { title: 'CSV Tryton', route: '/ventas_para_tryton', icon: 'mdi-file-table'},
             { title: 'Compra adm', route: '/compra_admin', icon: 'mdi-cart'},
              { title: 'Gestión de Productos', route: '/admin/products', icon: 'mdi-package-variant'},
              { title: 'Imágenes de Catálogo', route: '/admin/catalogue-images', icon: 'mdi-image-multiple'},
              { title: 'Ver Ventas por Catálogo', route: '/admin/catalog-sales', icon: 'mdi-cart-arrow-down'},
             { divider: true },
             { header: 'Sincronización Tryton' },
             { title: 'Importar Productos', route: '/sincronizar_productos_tryton', icon: 'mdi-download'},
             { title: 'Importar Clientes', route: '/sincronizar_clientes_tryton', icon: 'mdi-download'},
             { title: 'Exportar Ventas', route: '/sincronizar_ventas_tryton', icon: 'mdi-upload'},
             { title: 'Exportar Ventas Catálogo', route: '/sincronizar_catalog_sales_tryton', icon: 'mdi-upload'}
         ],
      }),
      computed: {
        isAdmin() {
          return this.user?.role === 'administrator';
        },
        filteredMenuItems() {
          if (this.user?.role === 'publico') {
            return this.menuItems.filter(item => item.route !== '/comprar');
          }
          return this.menuItems;
        },
      },
      mounted() {
       this.checkAuth();
       if (this.isAuthenticated) {
         this.fetchUser();
       }
     },
      watch: {
          group () {
              this.drawer = false
          },
          $route() {
            this.checkAuth();
            if (this.isAuthenticated && !this.user) {
              this.fetchUser();
            }
          },
      },
     methods: {
         checkAuth() {
           this.isAuthenticated = AuthService.isAuthenticated();
         },
          async fetchUser() {
            try {
              this.user = await this.api.getCurrentUser();
              this.authStore.setUser(this.user);
            } catch (error) {
              console.error('Error fetching user:', error);
            }
          },
         navigate(route) {
             this.$router.push(route);
         },
         navigateAdmin(route) {
             this.toggleAdminMenu();
             this.navigate(route);
         },
         toggleAdminMenu() {
             this.showAdminMenu = !this.showAdminMenu;
         },
         logout() {
            AuthService.logout();
            this.isAuthenticated = false;
            this.user = null;
            this.authStore.clearUser();
            this.$router.push('/');
          },
     }
  }
 </script>

