<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>

    <div class="graph-section">
      <button @click="openGraphDialog">
        {{ $t('falukant.moneyHistory.graph.open') }}
      </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>{{ translateActivity(entry.activity) }}</td>
          <td>{{ entry.moneyBefore != null ? Number(entry.moneyBefore).toLocaleString(locale, { style: 'currency', currency: 'EUR' }) : '---' }}</td>
          <td>{{ entry.moneyAfter != null ? Number(entry.moneyAfter).toLocaleString(locale, { style: 'currency', currency: 'EUR' }) : '---' }}</td>
          <td>{{ entry.changeValue != null ? Number(entry.changeValue).toLocaleString(locale, { style: 'currency', currency: 'EUR' }) : '---' }}</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>

    <MoneyHistoryGraphDialog ref="graphDialog" />
  </div>
</template>

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

export default {
  name: 'MoneyHistoryView',
  components: {
    StatusBar,
    MoneyHistoryGraphDialog,
  },
  computed: {
    locale() {
      return window.navigator.language || 'en-US';
    },
  },
  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);
      }
    },
    translateActivity(activity) {
      if (typeof activity === 'string') {
        const taxMatch = activity.match(/^tax from sales branch\s+(\d+)$/i);
        if (taxMatch) {
          return this.$t('falukant.moneyHistory.activities.taxFromSalesBranch', {
            branchId: taxMatch[1],
          });
        }

        const reputationMatch = activity.match(/^reputation action:\s*(.+)$/i);
        if (reputationMatch) {
          const actionKey = String(reputationMatch[1] || '').trim();
          let actionLabel = actionKey;
          if (actionKey) {
            const reputationKey = `falukant.reputation.actions.type.${actionKey}`;
            const reputationTranslation = this.$t(reputationKey);
            if (reputationTranslation !== reputationKey) {
              actionLabel = reputationTranslation;
            }
          }
          return this.$t('falukant.moneyHistory.activities.reputationAction', {
            action: actionLabel,
          });
        }
      }

      const candidates = [activity];

      if (typeof activity === 'string') {
        candidates.push(activity.replaceAll('_', ' '));
        candidates.push(activity.replaceAll(' ', '_'));
      }

      for (const candidate of candidates) {
        const key = `falukant.moneyHistory.activities.${candidate}`;
        const translation = this.$t(key);
        if (translation !== key) {
          return translation;
        }

        if (candidate.includes('.')) {
          const parts = candidate.split('.');
          const nestedKey = `falukant.moneyHistory.activities.${parts[0]}.${parts[1]}`;
          const nestedTranslation = this.$t(nestedKey);
          if (nestedTranslation !== nestedKey) {
            return nestedTranslation;
          }
        }
      }

      return activity;
    },
    openGraphDialog() {
      this.$refs.graphDialog.open();
    },
  },
};
</script>

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

.graph-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>
