<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>{{ 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>
  </div>
</template>

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

export default {
  name: 'MoneyHistoryView',
  components: {
    StatusBar,
  },
  computed: {
    locale() {
      return window.navigator.language || 'en-US';
    },
  },
  data() {
    return {
      filter: '',
      moneyHistory: {
        data: [],
        currentPage: 1,
        totalPages: 1,
      },
      productsById: {},
    };
  },
  async mounted() {
    await Promise.all([this.loadProducts(), this.fetchMoneyHistory(1)]);
  },
  methods: {
    async loadProducts() {
      try {
        const { data } = await apiClient.get('/api/falukant/products');
        const map = {};
        for (const p of (data || [])) {
          if (p && p.id != null && p.labelTr) {
            map[String(p.id)] = p.labelTr;
          }
        }
        this.productsById = map;
      } catch (e) {
        console.error('Error loading products for money history', e);
        this.productsById = {};
      }
    },
    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) {
      try {
        const raw = String(activity ?? '');
        // Handle legacy format: "tax from sale product 3"
        const m = raw.match(/^tax\s+from\s+sale\s+product\s+(\d+)$/i);
        if (m && m[1]) {
          const id = m[1];
          const labelTr = this.productsById[String(id)];
          const productName = labelTr ? this.$t(`falukant.product.${labelTr}`) : `#${id}`;
          return this.$t('falukant.moneyHistory.activities.taxFromSaleProduct', { product: productName });
        }
        // New/structured format: "taxFromSaleProduct.<labelTr>"
        if (raw.startsWith('taxFromSaleProduct.')) {
          const labelTr = raw.substring('taxFromSaleProduct.'.length);
          const productName = labelTr ? this.$t(`falukant.product.${labelTr}`) : labelTr;
          return this.$t('falukant.moneyHistory.activities.taxFromSaleProduct', { product: productName });
        }
      } catch (_) {
        // ignore and fall back
      }
      // Handle nested keys like "health.pill" -> "health.pill"
      const key = `falukant.moneyHistory.activities.${activity}`;
      const translation = this.$t(key);
      // If translation is the same as key, try nested structure
      if (translation === key && activity.includes('.')) {
        const parts = activity.split('.');
        const nestedKey = `falukant.moneyHistory.activities.${parts[0]}.${parts[1]}`;
        const nestedTranslation = this.$t(nestedKey);
        return nestedTranslation !== nestedKey ? nestedTranslation : activity;
      }
      return translation !== key ? translation : activity;
    },
  },
};
</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>