<script setup lang="ts">


import {computed, onMounted, ref} from "vue";
import BudgetTransactionView from "@/components/budgets/BudgetTransactionView.vue";
import IconField from "primevue/iconfield";
import InputIcon from "primevue/inputicon";
import InputText from "primevue/inputtext";
import {getTransactions} from "@/services/transactionService";
import {Transaction} from "@/models/Transaction";
import {useRoute} from "vue-router";

const loading = ref(false);
const searchText = ref("");

const route = useRoute()


const fetchCategories = async () => {
  loading.value = true
  try {
    const response = await getTransactions('INSTANT');
    transactions.value = response.data
    console.log(transactions.value)
  } catch (error) {
    console.error('Error fetching categories:', error);
  }
  loading.value = false
}

const tgname = computed(() => {
  if (window.Telegram.WebApp) {
    const tg = window.Telegram.WebApp;
    // tg.expand(); // Разворачиваем веб-приложение на весь экран

// Получаем информацию о пользователе и выводим её
    return tg.initDataUnsafe.user
  }
})

const transactions = ref<Transaction[]>([])

const filteredTransactions = computed(() => {
  if (searchText.value.length === 0) {
    return transactions.value;  // Return the full list when there's no search text
  } else {
    return transactions.value.filter(transaction => {
      const search = searchText.value.toLowerCase();
      return (
          transaction.transaction.comment.toLowerCase().includes(search) ||
          transaction.transaction.category.name.toLowerCase().includes(search)
      );
    });
  }
});

onMounted(async () => {
  await fetchCategories();
})

</script>

<template>
  <div class="px-4 bg-gray-100 h-full ">
    <!-- Заголовок -->
    {{tgname}}
    <h2 class="text-4xl mb-6  font-bold">Transaction list</h2>
    <div class="flex flex-col gap-2">
      <IconField>
        <InputIcon class="pi pi-search"/>
        <InputText v-model="searchText" placeholder="Search"></InputText>
      </IconField>

      <div class="mt-4">
        <BudgetTransactionView class="mb-2" v-for="transaction in filteredTransactions" :transaction="transaction"/>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>