<template>
    <div class="storage-section">
      <div class="storage-info">
        <p>
          {{ $t('falukant.branch.storage.currentCapacity') }}:
          <strong>{{ currentStorage }} / {{ maxStorage }}</strong>
        </p>
        <table>
          <thead>
            <tr>
              <th>{{ $t('falukant.branch.storage.stockType') }}</th>
              <th>{{ $t('falukant.branch.storage.totalCapacity') }}</th>
              <th>{{ $t('falukant.branch.storage.used') }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(usage, idx) in storageUsage" :key="idx">
              <td>{{ $t(`falukant.branch.stocktype.${usage.stockTypeLabelTr}`) }}</td>
              <td>{{ usage.totalCapacity }}</td>
              <td>{{ usage.used }}</td>
            </tr>
          </tbody>
        </table>
        <h4>{{ $t('falukant.branch.storage.availableToBuy') }}</h4>
        <table>
          <thead>
            <tr>
              <th>{{ $t('falukant.branch.storage.stockType') }}</th>
              <th>{{ $t('falukant.branch.storage.totalCapacity') }}</th>
            </tr>
          </thead>
          <tbody>
            <!-- Hier zeigen wir die gruppierten (nach Label) Einträge an -->
            <tr v-for="(group, i) in buyableUsage" :key="i">
              <td>{{ $t(`falukant.branch.stocktype.${group.stockTypeLabelTr}`) }}</td>
              <td>{{ group.totalQuantity }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="storage-market">
        <div class="buy-section">
          <label>{{ $t('falukant.branch.storage.selectStockType') }}</label>
          <!-- Auswahl basiert jetzt auf dem Label -->
          <select v-model="selectedBuyStockTypeLabelTr">
            <option v-for="group in buyableUsage" :key="group.stockTypeLabelTr" :value="group.stockTypeLabelTr">
              {{ $t(`falukant.branch.stocktype.${group.stockTypeLabelTr}`) }} - {{ getCostOfType(group.stockTypeLabelTr) }}
            </option>
          </select>
          <div>
            <label>{{ $t('falukant.branch.storage.buyAmount') }}</label>
            <input type="number" v-model.number="buyStorageAmount" :max="maxBuyableForSelectedBuy" min="1" />
            <button @click="onBuyStorage">
              {{ $t('falukant.branch.storage.buyStorageButton') }} ({{ buyCost }})
            </button>
          </div>
        </div>
        <div class="sell-section">
          <label>{{ $t('falukant.branch.storage.selectStockType') }}</label>
          <select v-model="selectedSellStockTypeId">
            <option v-for="type in storageUsage" :key="type.stockTypeId" :value="type.stockTypeId">
              {{ $t(`falukant.branch.stocktype.${type.stockTypeLabelTr}`) }} - {{ getCostOfTypeById(type.stockTypeId) }}
            </option>
          </select>
          <div>
            <label>{{ $t('falukant.branch.storage.sellAmount') }}</label>
            <input type="number" v-model.number="sellStorageAmount" :max="maxSellableForSelectedSell" min="1" />
            <button @click="onSellStorage">
              {{ $t('falukant.branch.storage.sellStorageButton') }} ({{ sellIncome }})
            </button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import apiClient from '@/utils/axios.js';
  export default {
    name: "StorageSection",
    props: { branchId: { type: Number, required: true } },
    data() {
      return {
        currentStorage: 0,
        maxStorage: 0,
        storageUsage: [],
        buyableUsage: [],
        buyStorageAmount: 0,
        sellStorageAmount: 0,
        stockTypes: [],
        selectedBuyStockTypeLabelTr: null,
        selectedSellStockTypeId: null,
      };
    },
    computed: {
      buyCost() {
        const cost = this.getCostOfType(this.selectedBuyStockTypeLabelTr);
        return this.buyStorageAmount * cost;
      },
      sellIncome() {
        const cost = this.getCostOfTypeById(this.selectedSellStockTypeId);
        return this.sellStorageAmount * cost;
      },
      maxBuyableForSelectedBuy() {
        const group = this.buyableUsage.find(g => g.stockTypeLabelTr === this.selectedBuyStockTypeLabelTr);
        return group ? group.totalQuantity : 0;
      },
      maxSellableForSelectedSell() {
        const usage = this.storageUsage.find(u => u.stockTypeId === this.selectedSellStockTypeId);
        return usage ? usage.totalCapacity : 0;
      },
    },
    async mounted() {
      await this.loadStorageData();
      await this.loadStockTypes();
    },
    methods: {
      async loadStorageData() {
        try {
          const { data } = await apiClient.get(`/api/falukant/storage/${this.branchId}`);
          this.currentStorage = data.totalUsedCapacity;
          this.maxStorage = data.maxCapacity;
          this.storageUsage = data.usageByType;
          const filteredBuyable = data.buyableByType.filter(item => item.quantity > 0);
          const grouped = {};
          filteredBuyable.forEach(item => {
            const key = item.stockTypeLabelTr;
            if (!grouped[key]) {
              grouped[key] = { stockTypeLabelTr: key, totalQuantity: 0, items: [] };
            }
            grouped[key].totalQuantity += item.quantity;
            grouped[key].items.push({ stockTypeId: item.stockTypeId, quantity: item.quantity });
          });
          this.buyableUsage = Object.values(grouped);
        } catch (error) {
          console.error('Error loading storage data:', error);
        }
      },
      async loadStockTypes() {
        try {
          const response = await apiClient.get('/api/falukant/stocktypes');
          this.stockTypes = response.data;
          if (this.stockTypes.length) {
            this.selectedBuyStockTypeLabelTr = this.stockTypes[0].labelTr;
            this.selectedSellStockTypeId = this.stockTypes[0].id;
          }
        } catch (error) {
          console.error('Error loading stock types:', error);
        }
      },
      async onBuyStorage() {
        if (!this.branchId || !this.buyStorageAmount || !this.selectedBuyStockTypeLabelTr) return;
        const group = this.buyableUsage.find(g => g.stockTypeLabelTr === this.selectedBuyStockTypeLabelTr);
        if (!group) return;
        let remainingAmount = this.buyStorageAmount;
        for (const item of group.items) {
          if (remainingAmount <= 0) break;
          const toBuy = Math.min(remainingAmount, item.quantity);
          try {
            await apiClient.post(`/api/falukant/storage`, {
              branchId: this.branchId,
              amount: toBuy,
              stockTypeId: item.stockTypeId
            });
          } catch (err) {
            console.error(err);
            alert('Error buying storage for one part of the order');
          }
          remainingAmount -= toBuy;
        }
        if (remainingAmount > 0) {
          alert(this.$t('falukant.branch.storage.notEnoughAvailable'));
        }
        this.loadStorageData();
      },
      onSellStorage() {
        if (!this.branchId || !this.sellStorageAmount || !this.selectedSellStockTypeId) return;
        apiClient.delete(`/api/falukant/storage`, {
          data: {
            branchId: this.branchId,
            amount: this.sellStorageAmount,
            stockTypeId: this.selectedSellStockTypeId
          }
        })
        .then(() => this.loadStorageData())
        .catch(err => {
          console.error(err);
          alert('Error selling storage');
        });
      },
      getCostOfType(labelTr) {
        const st = this.stockTypes.find(s => s.labelTr === labelTr);
        return st ? st.cost : 0;
      },
      getCostOfTypeById(stockTypeId) {
        const st = this.stockTypes.find(s => s.id === stockTypeId);
        return st ? st.cost : 0;
      },
    },
  };
  </script>
  
  <style scoped>
  .storage-section {
    border: 1px solid #ccc;
    margin: 10px 0;
    border-radius: 4px;
    padding: 10px;
  }
  .storage-info table, .storage-market table {
    width: 100%;
    border-collapse: collapse;
  }
  th, td {
    padding: 8px;
    border: 1px solid #ddd;
  }
  </style>
  