<template>
    <v-container>
      <v-card>
        <v-toolbar color="primary" flat>
          <v-toolbar-title>Gestão de Estudantes</v-toolbar-title>
          <v-spacer></v-spacer>
  
          <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"
          />
  
          <v-btn color="white" dark @click="openAddModal">+ Adicionar</v-btn>
        </v-toolbar>
  
        <!-- Tabela de Dados -->
        
        <Table 
          :users="students" 
          :loading="loading" 
          :error="error" 
          :searchQuery="searchQuery" 
          :headers="headers" 
          :page.sync="page" 
          :items-per-page="itemsPerPage" 
          :openEditPage="openEditPage" 
          :deleteStudent="deleteStudent" 
        />
      </v-card>
  
      <!-- Modal para adicionar/editar estudantes -->
      <UserModal 
        v-model:isModalOpen="isModalOpen" 
        :isEditMode="isEditMode" 
        :modalUser="modalStudent" 
        @save="saveStudent" 
      />
    </v-container>
  </template>
  
  <script>
  import { useStudentStore } from '../stores/students';
  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';
  import { useAuthStore } from '../stores/auth';

  export default {
    components: {
      UserModal,
      Table,
    },
    setup() {
      const router = useRouter();
      const studentStore = useStudentStore();
      const authStore = useAuthStore();

      const headers = reactive([
      { title: 'ID', value: 'id' },
      { title: 'Nome', 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 modalStudent = reactive({
        id: null,
        name: '',
        email: '',
      });
  
      const searchQuery = ref('');
  
      const openAddModal = () => {
        isEditMode.value = false;
        Object.assign(modalStudent, { id: null, name: '', email: '' });
        isModalOpen.value = true;
      };
  
      const openEditPage = (student) => {
        router.push({ name: 'editUser', params: { id: student.id } });
      };
  
      const saveStudent = async (studentData) => {
        if (isEditMode.value) {
          await studentStore.updateStudent(studentData.id, studentData);
        } else {
          await studentStore.createStudent(studentData);
        }
        closeModal();
      };
  
      const closeModal = () => {
        isModalOpen.value = false;
      };
  
      const deleteStudent = async (id) => {
        if (confirm('Tem certeza de que deseja excluir este estudante?')) {
          await studentStore.deleteStudent(id);
        }
      };
  
      onMounted(() => {
        studentStore.fetchStudents({ group_id: 2, instance_id: authStore.getInstance });
      });
  
      return {
        headers,
        students: computed(() => studentStore.allStudents),
        loading: computed(() => studentStore.loading),
        error: computed(() => studentStore.error),
        page,
        itemsPerPage,
        isModalOpen,
        isEditMode,
        modalStudent,
        searchQuery,
        openAddModal,
        openEditPage,
        saveStudent,
        deleteStudent,
      };
    },
  };
  </script>
  