<template>
  <div>
    <DefaultHeaderPage
      title="Alunos"
      show-filter-icon
      :filter-open="showFilter"
      @show-filter="showFilter = !showFilter"
    />

    <div class="q-pa-sm">
      <div class="filter-row">
        <template v-if="showFilter">
          <DefaultInputDatePicker
            v-model="startDate"
            v-model:untreated-date="startDateRaw"
            dense
            label="Data Inicial"
            color="secondary"
            class="filter-item"
          />

          <DefaultInputDatePicker
            v-model="endDate"
            v-model:untreated-date="endDateRaw"
            dense
            label="Data Final"
            color="secondary"
            class="filter-item"
          />

          <q-btn
            v-if="hasDateFilter"
            flat
            no-caps
            color="secondary"
            icon="mdi-filter-remove-outline"
            label="Limpar"
            @click="clearFilters"
          />
        </template>
      </div>
    </div>

    <div class="q-px-sm">
      <DefaultTable
        v-model:rows="rows"
        title="Lista de alunos"
        :columns
        descricao="Alunos"
        :feminino="false"
        no-api-call
        :add-item="canAdd"
        :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
                v-if="canEdit"
                outline
                icon="mdi-account-edit-outline"
                style="width: 36px"
                class="q-mr-sm"
                @click.prevent.stop="onEditStudent(row)"
              />
              <q-btn
                v-if="canDelete"
                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 { computed, 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 DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";
import { getStudents, deleteStudent } from "src/api/student";
import { userStore } from "src/stores/user";
import { permissionStore } from "src/stores/permission";

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 permissions = permissionStore();
const canAdd = computed(() =>
  permissions.getAccess("franchisee_students", "add"),
);
const canEdit = computed(() =>
  permissions.getAccess("franchisee_students", "edit"),
);
const canDelete = computed(() =>
  permissions.getAccess("franchisee_students", "delete"),
);

const rows = ref([]);
const isLoading = ref(false);
const showFilter = ref(false);
const startDate = ref(null);
const endDate = ref(null);
const startDateRaw = ref(null);
const endDateRaw = ref(null);

const hasDateFilter = computed(() => !!startDateRaw.value || !!endDateRaw.value);

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({
      contract_start_date: startDateRaw.value,
      contract_end_date: endDateRaw.value,
    });
  } catch (error) {
    console.error("Failed to load students:", error);
  } finally {
    isLoading.value = false;
  }
}

function clearFilters() {
  startDate.value = null;
  endDate.value = null;
  startDateRaw.value = null;
  endDateRaw.value = null;
}

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

watch([startDateRaw, endDateRaw], () => {
  loadStudents();
});

onMounted(loadStudents);
</script>

<style scoped>
.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.filter-item {
  flex: 1 1 200px;
  min-width: 180px;
  max-width: 300px;
}

@media (max-width: 599px) {
  .filter-item {
    flex: 1 1 100%;
    max-width: 100%;
  }
}
</style>
