<template>
  <div>
    <DefaultHeaderPage title="Alunos" show-filter-icon />

    <div class="q-px-sm">
      <DefaultTable
        v-model:rows="rows"
        title="Lista de alunos"
        :columns
        descricao="Alunos"
        :feminino="false"
        no-api-call
        add-item
        :loading="isLoading"
        @on-add-item="onAddStudent"
      >
        <template #body-cell-contato="{ row }">
          <q-td>
            <div>{{ row.phone }}</div>
            <div class="text-grey-6 text-caption">{{ row.city }}</div>
          </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="onEditStudent(row)"
              />
              <q-btn
                outline
                icon="mdi-trash-can-outline"
                style="width: 36px"
                class="q-mr-sm"
                @click.prevent.stop="onDeleteStudent(row)"
              />
            </q-item-section>
          </q-td>
        </template>
      </DefaultTable>
    </div>
  </div>
</template>

<script setup>
import { defineAsyncComponent, ref, onMounted, watch } from "vue";
import { useQuasar } from "quasar";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import { getStudents, deleteStudent } from "src/api/student";
import { userStore } from "src/stores/user";

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

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

const $q = useQuasar();
const store = userStore();

const rows = ref([]);
const isLoading = ref(false);

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

async function loadStudents() {
  isLoading.value = true;
  try {
    rows.value = await getStudents();
  } catch (error) {
    console.error("Failed to load students:", error);
  } finally {
    isLoading.value = false;
  }
}

function onAddStudent() {
  $q.dialog({
    component: AddEditStudentDialog,
  }).onOk(() => {
    loadStudents();
  });
}

function onEditStudent(student) {
  $q.dialog({
    component: EditStudentDialog,
    componentProps: { student },
  }).onOk(() => {
    loadStudents();
  });
}

function onDeleteStudent(student) {
  $q.dialog({
    title: "Excluir Aluno",
    message: `Deseja excluir o aluno "${student.name}"?`,
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    try {
      await deleteStudent(student.id);
      rows.value = rows.value.filter((r) => r.id !== student.id);
    } catch (e) {
      console.error(e);
      $q.notify({ type: "negative", message: "Erro ao excluir aluno." });
    }
  });
}

// Recarrega alunos sempre que a unidade ativa mudar
watch(
  () => store.selectedUnit?.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) loadStudents();
  },
);

onMounted(loadStudents);
</script>
