<template>
  <div>
    <DefaultTable
      v-model:rows="filteredRows"
      title="Lista de Usuários"
      :columns
      description="Usuários"
      no-api-call
      :add-item="canAdd"
      add-item-route="UserAddPage"
    >
      <template #body-cell-user_type="{ row }">
        <q-td align="left">{{ userTypeLabel(row.user_type) }}</q-td>
      </template>

      <template #body-cell-status="{ row }">
        <q-td align="center">
          <q-badge
            :color="row.status === 'ACTIVE' ? 'positive' : 'warning'"
            :label="row.status === 'ACTIVE' ? 'Ativo' : 'Inativo'"
          />
        </q-td>
      </template>

      <template #body-cell-actions="{ row }">
        <q-td auto-width>
          <q-item-section class="no-wrap" style="flex-direction: row">
            <q-btn
              v-if="canEdit"
              outline
              icon="mdi-account-edit-outline"
              style="width: 36px"
              class="q-mr-sm"
              @click.prevent.stop="onEdit(row)"
            />
            <q-btn
              v-if="canDelete"
              outline
              icon="mdi-trash-can-outline"
              style="width: 36px"
              class="q-mr-sm"
              @click.prevent.stop="onDelete(row)"
            />
          </q-item-section>
        </q-td>
      </template>
    </DefaultTable>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import { deleteUser, getUsers } from "src/api/user";
import { useQuasar } from "quasar";
import { permissionStore } from "src/stores/permission";

const router = useRouter();
const $q = useQuasar();
const permissions = permissionStore();
const canAdd = permissions.getAccess("franchisor_registrations", "add");
const canEdit = permissions.getAccess("franchisor_registrations", "edit");
const canDelete = permissions.getAccess("franchisor_registrations", "delete");

const funcaoSelected = ref(null);
const allUsers = ref([]);

const USER_TYPE_LABELS = {
  ADMIN: "Administrador (Franqueadora)",
  ADMIN_FRANCHISEE: "Administrador (Franqueada)",
};

const userTypeLabel = (type) => USER_TYPE_LABELS[type] ?? type;

const filteredRows = computed(() => {
  return allUsers.value.filter((row) => {
    if (funcaoSelected.value && row.user_type !== funcaoSelected.value.value)
      return false;
    return true;
  });
});

const columns = ref([
  { name: "name", label: "Nome", field: "name", align: "left" },
  { name: "email", label: "E-mail", field: "email", align: "left" },
  { name: "user_type", label: "Função", field: "user_type", align: "left" },
  { name: "status", label: "Status", field: "status", align: "center" },
  { name: "actions", label: "Ações", field: null, align: "center" },
]);

function onEdit(row) {
  router.push({ name: "UserEditPage", params: { id: row.id } });
}

function onDelete(row) {
  $q.dialog({
    title: "Excluir usuário",
    message: `Deseja excluir o usuário "${row.name}"?`,
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    await deleteUser(row.id);
    allUsers.value = allUsers.value.filter((user) => user.id !== row.id);
  });
}

onMounted(async () => {
  try {
    allUsers.value = await getUsers();
  } catch (error) {
    console.error("Failed to load users:", error);
  }
});
</script>
