<template>
  <div>
    <DefaultTable
      v-model:rows="filteredRows"
      title="Lista de Usuários"
      :columns
      description="Usuários"
      no-api-call
      add-item
      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
              outline
              icon="mdi-account-edit-outline"
              style="width: 36px"
              class="q-mr-sm"
              @click.prevent.stop="onEdit(row)"
            />
            <q-btn
              outline
              icon="mdi-trash-can-outline"
              style="width: 36px"
              class="q-mr-sm"
              @click.prevent.stop="() => {}"
            />
          </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 { getUsers } from "src/api/user";

const router = useRouter();

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 } });
}

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