<template>
  <div>
    <DefaultTable
      v-model:rows="rows"
      :columns="columns"
      no-api-call
      add-item
      :show-search-field="false"
      hide-no-data-label
      @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
          flat
          round
          dense
          icon="mdi-eye-outline"
          class="q-mr-xs"
          :disable="!row.file_url"
          @click.stop="openFile(row.file_url)"
        />
        <q-btn
          v-if="row.type !== 'contract'"
          flat
          round
          dense
          icon="mdi-file-edit-outline"
          class="q-mr-xs"
          @click.stop="openEditDialog(row)"
        />
        <q-btn
          flat
          round
          dense
          icon="mdi-trash-can-outline"
          @click.stop="confirmDelete(row)"
        />
      </template>
    </DefaultTable>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
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";
import { getStudentMedias, deleteStudentMedia } from "src/api/student_media";

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

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

const columns = [
  { name: "item", label: "Item", field: "id", align: "left" },
  { name: "date", label: "Data", field: "created_at", align: "left" },
  { name: "type", label: "Tipo", field: "type", align: "left" },
  { name: "name", label: "Nome", field: "name", align: "left" },
  { name: "actions", label: "Ações", field: null, align: "right" },
];

async function fetchMedias() {
  try {
    rows.value = await getStudentMedias(props.studentId);
  } catch (e) {
    console.error(e);
  }
}

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

function openEditDialog(row) {
  $q.dialog({
    component: EditStudentMediaDialog,
    componentProps: { media: row },
  }).onOk((updated) => {
    const index = rows.value.findIndex((r) => r.id === updated.id);
    if (index !== -1) rows.value[index] = updated;
  });
}

function openFile(url) {
  window.open(url, "_blank");
}

function confirmDelete(row) {
  $q.dialog({
    title: "Remover mídia",
    message: `Deseja remover "${row.name}"?`,
    ok: { color: "negative", label: "Remover" },
    cancel: { color: "primary", outline: true, label: "Cancelar" },
  }).onOk(async () => {
    try {
      await deleteStudentMedia(row.id);
      rows.value = rows.value.filter((r) => r.id !== row.id);
    } catch (e) {
      console.error(e);
    }
  });
}

onMounted(fetchMedias);

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