<template>
  <div>
    <DefaultTable
      v-model:rows="rows"
      title="Lista de Grupos"
      :columns
      description="Grupos"
      :female="false"
      :loading="loading"
      no-api-call
      :add-item="canAdd"
      @on-add-item="handleAdd"
    >
      <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-pencil-outline"
              style="width: 36px"
              class="q-mr-sm"
              @click.prevent.stop="handleEdit(row)"
            />
            <q-btn
              v-if="canDelete"
              outline
              icon="mdi-trash-can-outline"
              style="width: 36px"
              class="q-mr-sm"
              @click.prevent.stop="handleDelete(row)"
            />
          </q-item-section>
        </q-td>
      </template>
    </DefaultTable>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import AddEditGroupDialog from "../components/AddEditGroupDialog.vue";
import { getGroups, deleteGroup } from "src/api/group";
import { permissionStore } from "src/stores/permission";

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 rows = ref([]);
const loading = ref(false);

const columns = ref([
  { name: "name", label: "Nome", field: "name", align: "left" },
  { name: "active_units", label: "Unidades Ativas", field: "active_units", align: "center" },
  { name: "status", label: "Status", field: "status", align: "center" },
  { name: "actions", label: "Ações", field: null, align: "center" },
]);

async function fetchGroups() {
  loading.value = true;
  try {
    rows.value = await getGroups();
  } catch (error) {
    console.error("Failed to load groups:", error);
  } finally {
    loading.value = false;
  }
}

function handleAdd() {
  $q.dialog({ component: AddEditGroupDialog }).onOk(() => fetchGroups());
}

function handleEdit(row) {
  $q.dialog({ component: AddEditGroupDialog, componentProps: { group: row } }).onOk(() => fetchGroups());
}

function handleDelete(row) {
  $q.dialog({
    title: "Confirmar exclusão",
    message: `Deseja excluir o grupo "${row.name}"?`,
    ok: { color: "negative", label: "Excluir" },
    cancel: { color: "primary", outline: true, label: "Cancelar" },
  }).onOk(async () => {
    try {
      await deleteGroup(row.id);
      await fetchGroups();
    } catch (error) {
      console.error("Failed to delete group:", error);
    }
  });
}

onMounted(fetchGroups);
</script>
