<template>
  <div class="moneyflow">
    <StatusBar ref="statusBar" />
    <h2>{{ $t('falukant.moneyHistory.title') }}</h2>

    <div class="filter-section">
      <label>{{ $t('falukant.moneyHistory.filter') }}</label>
      <input v-model="filter" type="text" />
      <button @click="fetchMoneyHistory(1)">{{ $t('falukant.moneyHistory.search') }}</button>
    </div>

    <table>
      <thead>
        <tr>
          <th>{{ $t('falukant.moneyHistory.activity') }}</th>
          <th>{{ $t('falukant.moneyHistory.moneyBefore') }}</th>
          <th>{{ $t('falukant.moneyHistory.moneyAfter') }}</th>
          <th>{{ $t('falukant.moneyHistory.changeValue') }}</th>
          <th>{{ $t('falukant.moneyHistory.time') }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(entry, index) in moneyHistory.data" :key="index">
          <td>{{ $t(`falukant.moneyHistory.activities.${entry.activity}`) }}</td>
          <td>{{ entry.moneyBefore }}</td>
          <td>{{ entry.moneyAfter }}</td>
          <td>{{ entry.changeValue }}</td>
          <td>{{ new Date(entry.time).toLocaleString() }}</td>
        </tr>
      </tbody>
    </table>

    <div class="pagination">
      <button v-if="moneyHistory.currentPage > 1" @click="fetchMoneyHistory(moneyHistory.currentPage - 1)">
        {{ $t('falukant.moneyHistory.prev') }}
      </button>
      <span>
        {{ moneyHistory.currentPage }} / {{ moneyHistory.totalPages }}
      </span>
      <button v-if="moneyHistory.currentPage < moneyHistory.totalPages"
        @click="fetchMoneyHistory(moneyHistory.currentPage + 1)">
        {{ $t('falukant.moneyHistory.next') }}
      </button>
    </div>
  </div>
</template>

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

export default {
  name: 'MoneyHistoryView',
  components: {
    StatusBar,
  },
  data() {
    return {
      filter: '',
      moneyHistory: {
        data: [],
        currentPage: 1,
        totalPages: 1,
      },
    };
  },
  async mounted() {
    await this.fetchMoneyHistory(1);
  },
  methods: {
    async fetchMoneyHistory(page) {
      try {
        const response = await apiClient.post('/api/falukant/moneyhistory', {
          page,
          filter: this.filter,
        });
        this.moneyHistory = response.data;
      } catch (error) {
        console.error('Error fetching money history:', error);
      }
    },
  },
};
</script>

<style scoped>
.filter-section {
  margin-bottom: 1rem;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 1rem;
}

th,
td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 1rem;
}

h2 {
  padding-top: 20px;
}

.moneyflow {
  overflow: auto;
  height: 100%;
}
</style>