<template>
  <div>
    <DefaultHeaderPage title="Usuários" />

    <div class="q-px-sm">
      <DefaultTable
        :key="tableKey"
        title="Lista de Usuários"
        :columns="columns"
        :api-call="getUsers"
        descricao="usuários"
        :feminino="false"
        :add-item="canAdd"
        add-item-route="UserAddPage"
      >
        <template #body-cell-actions="{ row }">
          <q-td align="center">
            <q-btn
              v-if="canEdit"
              outline
              icon="mdi-account-edit-outline"
              style="width: 36px"
              @click.prevent.stop="onEdit(row)"
            />
          </q-td>
        </template>
      </DefaultTable>
    </div>
  </div>
</template>

<script setup>
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import { getUsers } from "src/api/user";

import { useRouter } from "vue-router";
import { formatDateYMDtoDMY } from "src/helpers/utils";
import { computed } from "vue";
import { userStore } from "src/stores/user";
import { permissionStore } from "src/stores/permission";

const router = useRouter();
const store = userStore();
const permissions = permissionStore();
const canAdd = computed(() => permissions.getAccess("franchisee_users", "add"));
const canEdit = computed(() => permissions.getAccess("franchisee_users", "edit"));
// Chave reativa: força remount do DefaultTable ao mudar de unidade
const tableKey = computed(() => store.selectedUnit?.id ?? 0);

const columns = [
  {
    name: "name",
    label: "Nome",
    field: "name",
    align: "left",
    sortable: true,
  },
  {
    name: "type",
    label: "Tipo de Usuário",
    field: (row) => row.user_type_label ?? row.user_type ?? "-",
    align: "left",
    sortable: true,
  },
  {
    name: "created_at",
    label: "Data de Cadastro",
    field: (row) => formatDateYMDtoDMY(row.created_at),
    align: "left",
    sortable: true,
  },
  {
    name: "actions",
    label: "Ações",
    field: null,
    align: "center",
    required: true,
  },
];

const onEdit = (row) => {
  router.push({ name: "UserEditPage", params: { id: row.id } });
};
</script>
