<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card style="min-width: 800px; max-width: 95vw">
      <DefaultDialogHeader
        :title="() => $t('import_log.history_title')"
        icon="mdi-clock-outline"
        @close="onDialogCancel"
      />

      <q-separator />

      <q-card-section class="q-pa-none">
        <DefaultTableServerSide
          :columns="columns"
          :api-call="apiCall"
          :add-item="false"
          :show-search-field="false"
        >
          <template #body-cell-imported_at="{ row }">
            <q-td>{{ formatDateTime(row.imported_at) }}</q-td>
          </template>

          <template #body-cell-user="{ row }">
            <q-td>{{ row.user?.name ?? '—' }}</q-td>
          </template>
        </DefaultTableServerSide>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { useDialogPluginComponent } from "quasar";
import { useI18n } from "vue-i18n";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import DefaultTableServerSide from "src/components/defaults/DefaultTableServerSide.vue";
import { getImportLogsPaginated } from "src/api/importLog";

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

defineEmits([...useDialogPluginComponent.emits]);

const { t } = useI18n();
const { dialogRef, onDialogHide, onDialogCancel } = useDialogPluginComponent();

const columns = [
  { name: "imported_at", label: t("import_log.date_time"),   field: "imported_at", align: "left",   sortable: false },
  { name: "user",        label: t("import_log.imported_by"), field: "user",        align: "left",   sortable: false },
  { name: "total",       label: t("import_log.total"),       field: "total",       align: "center", sortable: false },
  { name: "created",     label: t("import_log.created"),     field: "created",     align: "center", sortable: false },
  { name: "updated",     label: t("import_log.updated"),     field: "updated",     align: "center", sortable: false },
  { name: "inactivated", label: t("import_log.inactivated"), field: "inactivated", align: "center", sortable: false },
];

const apiCall = (params) => getImportLogsPaginated({ ...params, type: props.type });

const formatDateTime = (isoString) => {
  if (!isoString) return "—";
  const d = new Date(isoString);
  return d.toLocaleString("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};
</script>
