<template>
  <div>
    <DefaultTable
      v-model:rows="rows"
      title="Responsáveis"
      :columns
      descricao="responsáveis"
      :feminino="true"
      no-api-call
      add-item
      :show-search-field="false"
      @on-add-item="handleAdd"
    >
      <template #body-cell-actions="{ row }">
        <q-td align="center">
          <q-item-section class="no-wrap" style="flex-direction: row; gap: 4px">
            <q-btn
              outline
              icon="mdi-pencil-outline"
              style="width: 36px"
              @click.prevent.stop="handleEdit(row)"
            />
            <q-btn
              outline
              icon="mdi-trash-can-outline"
              style="width: 36px"
              @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 ResponsibleDialog from "src/pages/students/components/ResponsibleDialog.vue";
import {
  getStudentResponsible,
  deleteStudentResponsible,
} from "src/api/studentResponsible";

const props = defineProps({
  studentId: {
    type: Number,
    required: true,
  },
});

const $q = useQuasar();
const rows = ref([]);

const columns = ref([
  { name: "name", label: "Nome", field: "name", align: "left" },
  {
    name: "degree",
    label: "Grau de Parentesco",
    field: "degree",
    align: "left",
  },
  { name: "phone", label: "Telefone", field: "phone", align: "left" },
  { name: "email", label: "E-mail", field: "email", align: "left" },
  { name: "actions", label: "Ações", field: null, align: "center" },
]);

async function loadResponsibles() {
  rows.value = await getStudentResponsible(props.studentId);
}

onMounted(loadResponsibles);

function openDialog(responsible = null) {
  $q.dialog({
    component: ResponsibleDialog,
    componentProps: { studentId: props.studentId, responsible },
  }).onOk(loadResponsibles);
}

function handleAdd() {
  openDialog();
}

function handleEdit(responsible) {
  openDialog(responsible);
}

function handleDelete(responsible) {
  $q.dialog({
    title: "Excluir Responsável",
    message: `Deseja excluir o responsável "${responsible.name}"?`,
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    try {
      await deleteStudentResponsible(responsible.id);
      rows.value = rows.value.filter((r) => r.id !== responsible.id);
    } catch (e) {
      console.error(e);
      $q.notify({ type: "negative", message: "Erro ao excluir responsável." });
    }
  });
}
</script>
