<template>
  <v-card class="info">
    <!-- Navegação das Abas -->
    <v-tabs v-model="tab" light>
      <v-tab value="basic-info">Informações Básicas</v-tab>
      <v-tab value="contacts">Contatos</v-tab>
      <v-tab value="addresses">Endereços</v-tab>
      <v-tab value="licenses">Licenças</v-tab>
      <v-tab v-if="permissionsByRole || user?.permissions">Permissões</v-tab>
    </v-tabs>

    <!-- Conteúdo das Abas usando v-tabs-window -->
    <v-card-text>
      <v-tabs-window v-model="tab">
        <!-- Informações Básicas -->
        <v-tabs-window-item value="basic-info">
          <div class="d-flex align-center justify-space-between">
            <h3 class="ml-4">Informações Básicas</h3>
            <v-btn
              color="primary"
              icon
              class="mr-4"
              @click="openUserModal('edit', user)"
            >
              <v-icon>mdi-pencil</v-icon>
            </v-btn>
          </div>
          <v-list-item>
            <v-list-item-content>
              <v-list-item-title>Nome de Usuário:</v-list-item-title>
              <v-list-item-subtitle>{{ user?.username || "N/A" }}</v-list-item-subtitle>
            </v-list-item-content>
          </v-list-item>
        </v-tabs-window-item>

        <!-- Contatos -->
        <v-tabs-window-item value="contacts">
          <h3 class="ml-4">Contatos</h3>
          <v-list class="fund">
            <v-list-item v-for="(contact, index) in user?.contacts || []" :key="index">
              <v-list-item-content>
                <v-list-item-title><strong>Tipo: </strong>{{ contact.contact_type }}</v-list-item-title>
                <v-list-item-subtitle v-if="contact.description">
                  Observação: {{ contact.description }}
                </v-list-item-subtitle>
                <v-list-item-subtitle>
                  Fone: {{ contact.phone }}
                </v-list-item-subtitle>
              </v-list-item-content>
              <v-divider v-if="index !== user?.contacts.length - 1"></v-divider>
            </v-list-item>
          </v-list>
        </v-tabs-window-item>

        <!-- Endereços -->
        <v-tabs-window-item value="addresses">
          <h3 class="ml-4">Endereços</h3>
          <v-list class="fund">
            <v-list-item v-for="(address, index) in user?.addresses || []" :key="index">
              <v-list-item-content>
                <v-list-item-title><strong>Tipo: </strong>{{ address.type }}</v-list-item-title>
                <v-list-item-subtitle><strong>Endereço: </strong>{{ address.street }}</v-list-item-subtitle>
                <v-list-item-subtitle><strong>Cidade: </strong>{{ address.city }}</v-list-item-subtitle>
                <v-list-item-subtitle><strong>Estado: </strong>{{ address.state }}</v-list-item-subtitle>
                <v-list-item-subtitle><strong>País: </strong>{{ address.country }}</v-list-item-subtitle>
                <v-list-item-subtitle><strong>CEP: </strong>{{ address.zip_code }}</v-list-item-subtitle>
              </v-list-item-content>
              <v-divider v-if="index !== user?.addresses.length - 1"></v-divider>
            </v-list-item>
          </v-list>
        </v-tabs-window-item>

        <!-- Licenças -->
        <v-tabs-window-item value="licenses">
          <h3 class="ml-4">Licenças</h3>
          <v-list class="fund">
            <v-list-item v-for="(license, index) in user?.licenses || []" :key="index">
              <v-list-item-content>
                <v-list-item-title>Software: {{ license.service_name }}</v-list-item-title>
                <v-list-item-subtitle>Chave: {{ license.license_key }}</v-list-item-subtitle>
                <v-list-item-subtitle>Expiram em: {{ license.end_date }}</v-list-item-subtitle>
              </v-list-item-content>
            </v-list-item>
          </v-list>
        </v-tabs-window-item>

        <!-- Permissões -->
        <v-tabs-window-item value="permissions" v-if="permissionsByRole || user?.permissions">
          <h3 class="ml-4">Permissões</h3>
          <PermissionSwitch :permissionsData="permissionsList" />
        </v-tabs-window-item>
      </v-tabs-window>
    </v-card-text>
    <UserModal
      v-model:isModalOpen="isUserModalOpen"
      :isEditMode="userModalMode === 'edit'"
      :modalUser="selectedUser"
      @save="handleUserSave"
    />
  </v-card>
</template>

<script setup>
import { ref, computed } from 'vue';
import PermissionSwitch from '../PermissionSwitch.vue';
import UserModal from '../modals/UserModal.vue';
import { useUserStore } from '../../stores/users';
const emit = defineEmits(['user-updated']);

const props = defineProps({
  user: {
    type: Object,
    required: true
  },
  permissionsByRole: {
    type: Array,
    required: false
  }
});

const tab = ref("basic-info");
const isUserModalOpen = ref(false);
const userModalMode = ref('edit');
const selectedUser = ref({});

const permissionsList = computed(() => {
  return props.permissionsByRole || props.user?.permissions?.map(permission => 
    permission.permissions.map(p => p.type)
  ) || [];
});

const openUserModal = (mode, userData) => {
  userModalMode.value = mode;
  selectedUser.value = { ...userData };
  isUserModalOpen.value = true;
};

const handleUserSave = async (updatedUser) => {
  try {
    const userStore = useUserStore();
    const response = await userStore.updateUser(updatedUser.id, updatedUser);
    
    // Emit an event with the updated user data
    emit('user-updated', response.data);
    
    isUserModalOpen.value = false;
    userStore.fetchUsersHierarchy();
  } catch (error) {
    console.error('Erro ao salvar usuário', error);
  }
};

</script>

<style scoped>
h3 {
  margin-bottom: 20px;
}

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

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