<template>
  <div>
    <DefaultHeaderPage
      title="Tipos de Usuários do Sistema"
      :show-filter-icon="false"
    />

    <div class="q-px-sm">
      <DefaultTable
        ref="tableRef"
        title="Lista de Tipos de Usuários"
        :columns="columns"
        :api-call="getUserTypes"
        descricao="tipos"
        :feminino="false"
        add-item
        @on-add-item="onAdd"
      >
        <template #body-cell-actions="{ row }">
          <q-td auto-width>
            <q-btn
              v-if="!row.is_system"
              outline
              icon="mdi-trash-can-outline"
              style="width: 36px"
              color="negative"
              @click.prevent.stop="onDelete(row)"
            />
          </q-td>
        </template>
      </DefaultTable>
    </div>
  </div>
</template>

<script setup>
import { defineAsyncComponent, useTemplateRef } from "vue";
import { useQuasar } from "quasar";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import { getUserTypes, deleteUserType } from "src/api/user_type";

const AddUserTypeDialog = defineAsyncComponent(
  () => import("src/pages/user_types/components/AddUserTypeDialog.vue"),
);

const $q = useQuasar();
const tableRef = useTemplateRef("tableRef");

const columns = [
  {
    name: "label",
    label: "Nome",
    field: "label",
    align: "left",
    sortable: true,
  },
  {
    name: "slug",
    label: "Código",
    field: "slug",
    align: "left",
    sortable: true,
  },
  {
    name: "actions",
    label: "Ações",
    field: null,
    align: "center",
    required: true,
  },
];

const onAdd = () => {
  $q.dialog({ component: AddUserTypeDialog }).onOk(() => {
    tableRef.value?.refresh();
  });
};

const onDelete = (row) => {
  $q.dialog({
    title: "Confirmar exclusão",
    message: `Remover o tipo "${row.label}"?`,
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    await deleteUserType(row.id);
    tableRef.value?.refresh();
  });
};
</script>
