<template>
  <DialogWidget
    ref="dlg"
    name="falukant-messages"
    :title="'falukant.messages.title'"
    :isTitleTranslated="true"
    icon="falukant/messages24.png"
  :buttons="[{ text: 'message.close', action: 'close' }]"
    width="520px"
    height="420px"
  >
    <ul class="messages">
      <li v-for="n in messages" :key="n.id" :class="{ unread: !n.shown }">
        <div class="body">{{ $t(n.tr) }}</div>
        <div class="footer">
          <span>{{ formatDate(n.createdAt) }}</span>
        </div>
      </li>
      <li v-if="messages.length === 0" class="empty">{{ $t('falukant.messages.empty') }}</li>
    </ul>
    <div class="pagination" v-if="total > size">
      <button @click="firstPage" :disabled="!canPrev">«</button>
      <button @click="prevPage" :disabled="!canPrev">‹</button>
      <span>
        <input type="number" min="1" :max="totalPages" v-model.number="pageInput" @change="goToPage(pageInput)" />
        / {{ totalPages }}
      </span>
      <button @click="nextPage" :disabled="!canNext">›</button>
      <button @click="lastPage" :disabled="!canNext">»</button>
    </div>
  </DialogWidget>
  </template>

<script>
import DialogWidget from '@/components/DialogWidget.vue';
import apiClient from '@/utils/axios.js';

export default {
  name: 'FalukantMessagesDialog',
  components: { DialogWidget },
  data() {
    return {
      messages: [],
      page: 1,
      size: 10,
      total: 0,
  pageInput: 1,
    };
  },
  methods: {
    async open() {
      this.page = 1;
  this.pageInput = 1;
      await this.load();
      this.$refs.dlg.open();
      // mark unread as shown
      try { await apiClient.post('/api/falukant/notifications/mark-shown'); } catch {}
    },
    async load() {
      try {
        const { data } = await apiClient.get('/api/falukant/notifications/all', { params: { page: this.page, size: this.size } });
        if (data && Array.isArray(data.items)) {
          this.messages = data.items;
          this.total = data.total || 0;
        } else {
          this.messages = Array.isArray(data) ? data : [];
          this.total = this.messages.length;
        }
      } catch (e) {
        console.error('Failed to load messages', e);
        this.messages = [];
        this.total = 0;
      }
    },
    nextPage() {
      if (this.page < this.totalPages) {
        this.page++;
        this.pageInput = this.page;
        this.load();
      }
    },
    prevPage() {
      if (this.page > 1) {
        this.page--;
        this.pageInput = this.page;
        this.load();
      }
    },
    firstPage() {
      if (this.page !== 1) {
        this.page = 1;
        this.pageInput = 1;
        this.load();
      }
    },
    lastPage() {
      if (this.page !== this.totalPages) {
        this.page = this.totalPages;
        this.pageInput = this.page;
        this.load();
      }
    },
    goToPage(val) {
      let v = Number(val) || 1;
      if (v < 1) v = 1;
      if (v > this.totalPages) v = this.totalPages;
      if (v !== this.page) {
        this.page = v;
        this.pageInput = v;
        this.load();
      } else {
        this.pageInput = v;
      }
    },
    formatDate(dt) {
      try {
        return new Date(dt).toLocaleString();
      } catch { return dt; }
    }
  },
  computed: {
    totalPages() {
      return Math.max(1, Math.ceil(this.total / this.size));
  },
  canPrev() { return this.page > 1; },
  canNext() { return this.page < this.totalPages; }
  }
};
</script>

<style scoped>
.messages {
  list-style: none;
  padding: 0;
  margin: 0;
}
.messages > li { border: 1px solid #7BBE55; margin-bottom: .25em; padding: .5em; }
.messages > li.unread { font-weight: bold; }
.messages > li .footer { color: #f9a22c; font-size: .8em; margin-top: .3em; display: flex; }
.messages > li .footer span:first-child { flex: 1; }
.empty { text-align: center; color: #777; padding: 1em; }
.pagination {
  display: flex;
  justify-content: center;
  gap: .5em;
  margin-top: .5em;
}
.pagination button { padding: .25em .6em; }
.pagination input[type="number"] { width: 4em; text-align: right; }
</style>
