<template>
  <div>
    <q-banner
      v-if="required && !loading && rows.length === 0"
      class="bg-orange-1 text-orange-10 q-mb-md"
      rounded
    >
      Este aluno é menor de idade e precisa ter ao menos um responsável.
    </q-banner>

    <DefaultTable
      v-model:rows="rows"
      :add-item="canAdd"
      :columns="columns"
      :feminino="true"
      :show-search-field="false"
      descricao="responsáveis"
      no-api-call
      title="Responsáveis"
      @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
              v-if="canEdit"
              icon="mdi-pencil-outline"
              outline
              style="width: 36px"
              @click.prevent.stop="handleEdit(row)"
            />

            <q-btn
              v-if="canDelete"
              icon="mdi-trash-can-outline"
              outline
              style="width: 36px"
              @click.prevent.stop="handleDelete(row)"
            />
          </q-item-section>
        </q-td>
      </template>
    </DefaultTable>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";

import {
  deleteStudentResponsible,
  getStudentResponsible,
} from "src/api/studentResponsible";

import { permissionStore } from "src/stores/permission";
import { useQuasar } from "quasar";

import DefaultTable from "src/components/defaults/DefaultTable.vue";
import ResponsibleDialog from "src/pages/students/components/ResponsibleDialog.vue";

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

const $q = useQuasar();

const permissions = permissionStore();

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

const canAdd = computed(() =>
  permissions.getAccess("franchisee_students", "add"),
);

const canDelete = computed(() =>
  permissions.getAccess("franchisee_students", "delete"),
);

const canEdit = computed(() =>
  permissions.getAccess("franchisee_students", "edit"),
);

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

const handleAdd = () => {
  openDialog();
};

const handleDelete = (responsible) => {
  if (props.required && rows.value.length === 1) {
    $q.notify({
      message:
        "O aluno menor de idade precisa ter ao menos um responsável.",
      type: "warning",
    });

    return;
  }

  $q.dialog({
    cancel: true,
    message: `Deseja excluir o responsável "${responsible.name}"?`,
    persistent: true,
    title: "Excluir Responsável",
  }).onOk(async () => {
    try {
      await deleteStudentResponsible(responsible.id);

      rows.value = rows.value.filter(
        (item) => item.id !== responsible.id,
      );
    } catch (error) {
      console.error(error);

      $q.notify({
        message: "Erro ao excluir responsável.",
        type: "negative",
      });
    }
  });
};

const handleEdit = (responsible) => {
  openDialog(responsible);
};

const loadResponsibles = async () => {
  loading.value = true;

  try {
    rows.value = await getStudentResponsible(
      props.studentId,
    );
  } finally {
    loading.value = false;
  }
};

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

const validateRequired = async (
  required = props.required,
) => {
  await loadResponsibles();

  return !required || rows.value.length > 0;
};

onMounted(loadResponsibles);

defineExpose({
  validateRequired,
});
</script>