<template>
  <v-container class="tab">
    <v-card>
      <v-toolbar class="info"  flat>
        <v-toolbar-title class="title">Gestão de Usuários</v-toolbar-title>
        <v-spacer></v-spacer>

        <!-- Barra de Pesquisa Compacta Alinhada à Direita -->
        <v-text-field 
          v-model="searchQuery" 
          :loading="loading" 
          append-inner-icon="mdi-magnify" 
          density="compact"
          variant="solo" 
          label="Pesquisar por nome" 
          hide-details 
          single-line 
          class="ml-auto"
          @click:append-inner="onClick" 
        />

        <v-btn color="white" dark @click="openAddModal">+ Adicionar</v-btn>
      </v-toolbar>

      <!-- Tabela de Dados -->
      <Table class="dados"
        :users="users" 
        :loading="loading" 
        :error="error" 
        :searchQuery="searchQuery" 
        :headers="headers" 
        :page.sync="page" 
        :items-per-page="itemsPerPage" 
        :openEditPage="openEditPage" 
        :deleteUser="deleteUser" 
      />
    </v-card>

    <!-- Modal para adicionar/editar usuários -->
    <UserModal 
      v-model:isModalOpen="isModalOpen" 
      :isEditMode="isEditMode" 
      :modalUser="modalUser" 
      @save="saveUser" 
    />
  </v-container>
</template>

<script>
import { useUserStore } from '../stores/users';
import { computed, onMounted, reactive, ref } from 'vue';
import UserModal from '../components/modals/UserModal.vue'; 
import Table from '../components/users/Table.vue'; // Importe o novo componente
import { useRouter } from 'vue-router';

export default {
  components: {
    UserModal, 
    Table, // Registre o componente UserTable
  },
  setup() {
    const router = useRouter()
    const userStore = useUserStore();

    const headers = reactive([
      { title: 'ID', value: 'id' },
      { title: 'Usuário', value: 'username' },
      { title: 'Email', value: 'email' },
      {
        title: 'Ações',
        value: 'actions',
        align: 'end',
        sortable: false,
      },
    ]);

    const page = ref(1);
    const itemsPerPage = ref(10);

    const isModalOpen = ref(false);
    const isEditMode = ref(false);
    const modalUser = reactive({
      id: null,
      username: '',
      email: '',
    });

    const searchQuery = ref('');

    const openAddModal = () => {
      isEditMode.value = false;
      Object.assign(modalUser, { id: null, username: '', email: '' });
      isModalOpen.value = true;
    };

    const openEditPage = (user) => {
      router.push({ name: 'editUser', params: { id: user.id } });
    };

    const saveUser = async (userData) => {
      if (isEditMode.value) {
        await userStore.updateUser(userData.id, userData);
      } else {
        await userStore.createUser(userData);
      }
      closeModal();
    };

    const closeModal = () => {
      isModalOpen.value = false;
    };

    const deleteUser = async (id) => {
      if (confirm('Tem certeza de que deseja excluir este usuário?')) {
        await userStore.deleteUser(id);
      }
    };

    onMounted(() => {
      userStore.fetchUsersHierarchy();
    });

    return {
      headers,
      users: computed(() => userStore.allUsers),
      loading: computed(() => userStore.loading),
      error: computed(() => userStore.error),
      page,
      itemsPerPage,
      isModalOpen,
      isEditMode,
      modalUser,
      searchQuery,
      openAddModal,
      openEditPage,
      saveUser,
      deleteUser,
    };
  },
};
</script>

<style scoped>

.info{
  color: rgba(108,0,181);
  background-color: rgba(76,201,240);
  background: linear-gradient(145deg, #eeeded, #ffffff);
  box-shadow:  20px 20px 60px #d9d9d9,
              -20px -20px 60px #ffffff;
}

.dados{
  font-size: 17px;
  color: rgba(108,0,181);
  background-color: rgba(76,201,240);
  background: linear-gradient(145deg, #eeeded, #ffffff);
  box-shadow:  20px 20px 60px #d9d9d9,
              -20px -20px 60px #ffffff;
}

.title {
  font-size: 25px;
  font-weight: 600;
}

.fund {
  border-radius: 15px;
  background: linear-gradient(45deg, #e6e6e6, #ffffff);
}
</style>
  

