<template>
  <div class="user-management">
    <!-- Header da página -->
    <div class="header-container">
      <div class="header-left">
        <div class="icon-wrapper">
          <v-icon color="primary" size="32">mdi-account-multiple</v-icon>
        </div>
        <div class="header-title">
          <h1>Sistema de Ponto | Admin</h1>
        </div>
      </div>
      <div class="header-right">
        <v-btn variant="text" prepend-icon="mdi-arrow-left" class="back-button" to="/dashboard">
          Voltar para Dashboard
        </v-btn>
        <v-btn color="primary" prepend-icon="mdi-plus" class="new-user-btn" @click="openDialog('user', 'create')">
          Novo Colaborador
        </v-btn>
        
        <v-badge dot color="error" class="notification-badge">
            <v-icon>mdi-bell</v-icon>
          </v-badge>
          <div class="admin-profile">
            <v-avatar class="mr-2" color="primary" size="40">
              <v-img src="/api/placeholder/40/40" alt="Administrador"></v-img>
            </v-avatar>
            <div class="admin-info">
              <span class="admin-name">Administrador</span>
              <span class="admin-role">Gestor</span>
            </div>
            <v-icon>mdi-chevron-down</v-icon>
          </div>
      </div>
    </div>

    <!-- Título e descrição da seção -->
    <div class="section-header">
      <h2>Gerenciamento de Colaboradores</h2>
      <p class="section-description">Gerencie os usuários do sistema</p>
    </div>

    <!-- Filtro e busca -->
    <div class="filter-bar">
      <v-text-field
        v-model="filters.user"
        prepend-inner-icon="mdi-magnify"
        label="Buscar colaboradores..."
        hide-details
        density="comfortable"
        class="search-input"
        variant="outlined"
      />
      <div class="status-toggle">
        <v-btn-toggle v-model="filters.status" mandatory density="comfortable">
          <v-btn value="all">Todos</v-btn>
          <v-btn value="Ativo">Ativos</v-btn>
          <v-btn value="Inativo">Inativos</v-btn>
        </v-btn-toggle>
      </div>
    </div>

    <!-- Card principal -->
    <v-card class="main-card" elevation="1">
      <div class="card-header">
        <h3>Lista de Colaboradores</h3>
        <p class="card-description">Visualize, edite ou desative colaboradores</p>
      </div>

      <v-data-table
        :headers="headers.users"
        :items="filteredUsers"
        :loading="loading.users"
        :items-per-page="itemsPerPage"
        :page.sync="page"
        class="user-table"
      >
        <template v-slot:item.status="{ item }">
          <div class="status-cell">
            <v-chip
            :style="{
              backgroundColor: item.status ==='Ativo' ? '#2563EB' : 'grey',
              color: 'white',
              borderRadius: '999px',
              fontWeight: '600',
              padding: '0 12px',
              height: '32px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }"
            size="small"
          >
            {{ item.status }}
            </v-chip>
          </div>
        </template>

        <template v-slot:item.actions="{ item }">
          <div class="action-buttons">
            <v-btn icon variant="text" color="black" @click="openEditPage('user', item)">
              <v-icon size="small">mdi-pencil-outline</v-icon>
            </v-btn>
            <v-btn icon variant="text" color="error" @click="deleteUser(item.id)">
              <v-icon size="small">mdi-delete-outline</v-icon>
            </v-btn>
          </div>
        </template>
      </v-data-table>
    </v-card>

    <!-- Modal de Usuário -->
    <UserModal
      v-model:isModalOpen="dialogs.user"
      :isEditMode="isEditing"
      :modalUser="forms.user"
      @user-updated="loadUsers"
    />
  </div>
</template>

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

export default {
  name: 'UserManagement',
  components: {
    UserModal
  },
  setup() {
    const router = useRouter();
    const userStore = useUserStore();

    const isEditing = ref(false);
    const dialogs = ref({ user: false });
    const page = ref(1);
    const itemsPerPage = ref(10);
    const filters = ref({ user: '', status: 'all' });
    const users = ref([]);
    const loading = ref({ users: false });

    const forms = ref({
      user: {
        id: null,
        username: '',
        email: '',
        department: '',
        cargo: '',
        status: 'Ativo',
        shift: '',
        admission_date: '',
      }
    });

    const headers = ref({
      users: [
        { title: 'ID', key: 'id' },
        { title: 'Name', key: 'username' },
        { title: 'E-mail', key: 'email' },
        { title: 'Cargo', key: 'cargo' },
        { title: 'Departamento', key: 'department' },
        { title: 'Escala', key: 'shift' },
        { title: 'Status', key: 'status' },
        { title: 'Ações', key: 'actions', sortable: false, align: 'end' }
      ]
    });

    const filteredUsers = computed(() => {
      return users.value.filter(user => {
        const matchesSearch = user.username?.toLowerCase().includes(filters.value.user.toLowerCase()) ||
                              user.email?.toLowerCase().includes(filters.value.user.toLowerCase());

        const matchesStatus =
          filters.value.status === 'all' ||
          (filters.value.status === 'Ativo' && user.status === 'Ativo') ||
          (filters.value.status === 'Inativo' && user.status === 'Inativo');

        return matchesSearch && matchesStatus;
      });
    });

    const loadUsers = async () => {
      try {
        loading.value.users = true;
        const usersData = await userStore.catchUsers();
        users.value = usersData;
      } catch (error) {
        console.error('Erro ao carregar usuários:', error);
      } finally {
        loading.value.users = false;
      }
    };

    const openDialog = (type, action, item = null) => {
      isEditing.value = action === 'edit';
      forms.value[type] = item
        ? { ...item }
        : { id: null, username: '', email: '', department: '', cargo: '', status: 'Ativo', shift: '', admission_date: '' };
      dialogs.value[type] = true;
    };

    const openEditPage = (type, item) => {
      openDialog(type, 'edit', item);
    };

    const deleteUser = async (id) => {
      try {
        await userStore.deleteUser(id);
        await loadUsers();
      } catch (error) {
        console.error('Erro ao excluir usuário:', error);
      }
    };

    onMounted(() => {
      loadUsers();
    });

    return {
      isEditing,
      dialogs,
      filters,
      users,
      forms,
      headers,
      page,
      itemsPerPage,
      loading,
      filteredUsers,
      openDialog,
      openEditPage,
      deleteUser,
      loadUsers
    };
  }
};
</script>

<style scoped>
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 16px;
}
.search-input {
  flex-grow: 1;
  max-width: 850px;
}
.status-toggle {
  background-color: #f3f4f6;
  border-radius: 8px;
  padding: 4px;
  display: flex;
  align-items: center;
}
.status-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}
.user-management {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Roboto, Arial, sans-serif;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eaecef;
}

.header-left {
  display: flex;
  align-items: center;
}

.icon-wrapper {
  background-color: #e3f2fd;
  border-radius: 8px;
  padding: 12px;
  margin-right: 12px;
}

.header-title h1 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #1e293b;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  color: #1976d2;
}

.new-user-btn {
  background-color: #1976d2;
  color: white;
}

.section-header {
  margin-bottom: 24px;
}

.section-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 8px 0;
}

.section-description {
  font-size: 14px;
  color: #64748b;
  margin: 0;
}

.main-card {
  border-radius: 12px;
  overflow: hidden;
  background-color: white;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.card-header {
  padding: 24px;
  border-bottom: 1px solid #eaecef;
}

.card-header h3 {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #1e293b;
}

.card-description {
  font-size: 14px;
  color: #64748b;
  margin: 0;
}

.user-table :deep(th) {
  font-weight: 600;
  color: #1e293b;
  font-size: 14px;
}

.user-table :deep(td) {
  font-size: 14px;
  color: #1e293b;
  padding: 16px;
  height: 64px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.admin-profile {
  display: flex;
  align-items: center;
  margin-left: 16px;
  cursor: pointer;
}

.admin-info {
  display: flex;
  flex-direction: column;
  margin: 0 8px;
}

.admin-name {
  font-size: 14px;
  font-weight: 500;
  color: #1e293b;
}

.admin-role {
  font-size: 12px;
  color: #64748b;
}

.notification-badge {
  margin: 0 8px;
}

</style>
