<template>
  <div>
    <DefaultTable
      v-model:rows="rows"
      :add-item="canAdd"
      :columns="columns"
      :feminino="true"
      :show-search-field="false"
      descricao="mídias"
      no-api-call
      title="Mídias"
      @on-add-item="openAddDialog"
    >
      <template #body-cell-item="{ rowIndex }">
        <q-td>
          {{ rowIndex + 1 }}
        </q-td>
      </template>

      <template #body-cell-type="{ row }">
        <q-td>
          <q-badge
            :color="row.type === 'contract' ? 'info' : 'primary'"
            :label="row.type === 'contract' ? 'Contrato' : 'Mídia'"
          />
        </q-td>
      </template>

      <template #body-cell-name="{ row }">
        <q-td>
          {{ row.name ?? "—" }}
        </q-td>
      </template>

      <template #body-cell-actions="{ row }">
        <q-btn
          class="q-mr-xs"
          dense
          flat
          icon="mdi-eye-outline"
          round
          :disable="!row.file_url"
          @click.stop="openFile(row.file_url)"
        />

        <q-btn
          v-if="canEdit && row.type !== 'contract'"
          class="q-mr-xs"
          dense
          flat
          icon="mdi-file-edit-outline"
          round
          @click.stop="openEditDialog(row)"
        />

        <q-btn
          v-if="canDelete"
          dense
          flat
          icon="mdi-trash-can-outline"
          round
          @click.stop="confirmDelete(row)"
        />
      </template>
    </DefaultTable>
  </div>
</template>

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

import {
  deleteStudentMedia,
  getStudentMedias,
} from "src/api/student_media";

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

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

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

const $q = useQuasar();

const permissions = permissionStore();

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: "id",
    label: "Item",
    name: "item",
  },
  {
    align: "left",
    field: "created_at",
    label: "Data",
    name: "date",
  },
  {
    align: "left",
    field: "type",
    label: "Tipo",
    name: "type",
  },
  {
    align: "left",
    field: "name",
    label: "Nome",
    name: "name",
  },
  {
    align: "right",
    field: null,
    label: "Ações",
    name: "actions",
  },
];

const confirmDelete = (row) => {
  $q.dialog({
    cancel: {
      color: "primary",
      label: "Cancelar",
      outline: true,
    },
    message: `Deseja remover "${row.name}"?`,
    ok: {
      color: "negative",
      label: "Remover",
    },
    title: "Remover mídia",
  }).onOk(async () => {
    try {
      await deleteStudentMedia(row.id);

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

const fetchMedias = async () => {
  try {
    rows.value = await getStudentMedias(
      props.studentId,
    );
  } catch (error) {
    console.error(error);
  }
};

const openAddDialog = () => {
  $q.dialog({
    component: AddStudentMediaDialog,
    componentProps: {
      studentId: props.studentId,
    },
  }).onOk((result) => {
    rows.value.unshift(result);
  });
};

const openEditDialog = (row) => {
  $q.dialog({
    component: EditStudentMediaDialog,
    componentProps: {
      media: row,
    },
  }).onOk((updatedMedia) => {
    const index = rows.value.findIndex(
      (media) => media.id === updatedMedia.id,
    );

    if (index !== -1) {
      rows.value[index] = updatedMedia;
    }
  });
};

const openFile = (url) => {
  window.open(url, "_blank");
};

onMounted(fetchMedias);

defineExpose({
  refresh: fetchMedias,
});
</script>