<template>
    <v-container>
      <v-card>
        <v-toolbar color="primary" flat>
          <v-toolbar-title>Gestão de Ambientes</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"
            @click:append-inner="handleSearch"
          />
          
          <v-btn color="white" dark @click="openAddModal">+ Adicionar Ambiente</v-btn>
        </v-toolbar>
  
        <Table 
          :items="spaces"
          :loading="loading"
          :error="error"
          :searchQuery="searchQuery"
          :headers="headers"
          :page="page"
          :itemsPerPage="itemsPerPage"
          :totalItems="totalItems"
          :filterField="filterField"
          @update:page="handlePageChange"
          @update:items-per-page="handleItemsPerPageChange"
          :openEditPage="openEditPage"
          :deleteItem="deleteSpace"
      />
      </v-card>
  
      <SpaceModal
        v-model:isModalOpen="isModalOpen"
        :isEditMode="isEditMode"
        :modalSpace="modalSpace"
        @save="saveSpace"
      />
    </v-container>
  </template>
  
  <script>
  import { useSpaceStore } from '../stores/spaces';
  import { computed, onMounted, reactive, ref, watch } from 'vue';
  import SpaceModal from '../components/modals/SpaceModal.vue';
  import Table from '../components/Table.vue';
  import { useRouter } from 'vue-router';
  
  export default {
    components: {
      SpaceModal,
      Table,
    },
    
    setup() {
      const router = useRouter()
      const spaceStore = useSpaceStore();
      const spaces = computed(() => spaceStore.spaces);
      

      const headers = reactive([
        { title: 'ID', value: 'id' },
        { title: 'Nome do Ambiente', value: 'name' },
        { title: 'Descrição', value: 'description' },
        { title: 'Data de Criação', value: 'created_at' },
        {
          title: 'Ações',
          value: 'actions',
          align: 'end',
          sortable: false,
        },
      ]);
  
      const page = ref(1);
      const itemsPerPage = ref(10);
      const searchQuery = ref('');
      const totalItems = computed(() => spaceStore.totalItems);
  
      const isModalOpen = ref(false);
      const isEditMode = ref(false);
      const modalSpace = reactive({
        id: null,
        name: '',
        description: '',
        service_instance_id: null,
      });
  
      // Atualiza a lista quando mudar a página ou itens por página
      const fetchPageData = () => {
        spaceStore.fetchSpaces({
          page: page.value,
          per_page: itemsPerPage.value,
          search: searchQuery.value
        });

      };
  
      const handlePageChange = (newPage) => {
        page.value = newPage;
        fetchPageData();
      };
  
      const handleItemsPerPageChange = (newItemsPerPage) => {
        itemsPerPage.value = newItemsPerPage;
        page.value = 1; // Reset to first page
        fetchPageData();
      };
  
      const handleSearch = () => {
        page.value = 1; // Reset to first page when searching
        fetchPageData();
      };
  
      // Watch para mudanças na pesquisa com debounce
      let searchTimeout;
      watch(searchQuery, () => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
          handleSearch();
        }, 500);
      });
  
      const openAddModal = () => {
        isEditMode.value = false;
        Object.assign(modalSpace, { 
          id: null, 
          name: '', 
          description: '', 
          service_instance_id: null 
        });
        isModalOpen.value = true;
      };
  
      const openEditPage = (space) => {
        router.push({ name: 'editSpace', params: { id: space.id } });
      };
  
      const saveSpace = async (spaceData) => {
        if (isEditMode.value) {
          await spaceStore.updateSpace(spaceData.id, spaceData);
        } else {
          await spaceStore.createSpace(spaceData);
        }
        isModalOpen.value = false;
        fetchPageData(); // Recarrega a página atual
      };
  
      const deleteSpace = async (id) => {
        if (confirm('Tem certeza de que deseja excluir este ambiente?')) {
          await spaceStore.deleteSpace(id);
          fetchPageData(); // Recarrega a página atual
        }
      };
  
      onMounted(async () => {
      await spaceStore.fetchSpaces({
        page: 1,
        per_page: 10,
        search: ''
      });
      
      // Debug logs
      console.log('Store state:', spaceStore.$state);
      console.log('Computed spaces:', spaces.value);
    });

  
      return {
        headers,
        spaces,
        totalItems: computed(() => spaceStore.total), // Use total directly
        loading: computed(() => spaceStore.loading),
        error: computed(() => spaceStore.error),
        totalItems,
        page,
        itemsPerPage,
        isModalOpen,
        isEditMode,
        modalSpace,
        searchQuery,
        openAddModal,
        openEditPage,
        saveSpace,
        deleteSpace,
        handlePageChange,
        handleItemsPerPageChange,
        handleSearch,
      };
    },
  };
  </script>