<template>
  <Toast/>
  <div v-if="loading" class="relative w-full h-screen">
    <!-- Полупрозрачный белый фон -->
    <div class="absolute top-0 left-0 w-full h-full bg-white opacity-50 z-0"></div>

    <!-- Спиннер поверх -->
    <div class="absolute top-0 left-0 w-full h-full flex items-center justify-center z-50">
      <ProgressSpinner
          style="width: 50px; height: 50px;"
          strokeWidth="8"
          fill="transparent"
          animationDuration=".5s"
          aria-label="Custom ProgressSpinner"
      />
    </div>
  </div>

  <div v-else class="px-4 bg-gray-100 h-full ">
    <div v-if="updateLoading" class="absolute top-0 left-0 w-full h-full flex items-center justify-center z-50">
      <ProgressSpinner
          v-if="updateLoading"
          class="absolute top-0 left-0 w-full h-full flex items-center justify-center z-50"
          style="width: 50px; height: 50px;"
          strokeWidth="8"
          fill="transparent"
          animationDuration=".5s"
          aria-label="Custom ProgressSpinner"
      />
    </div>
    <div :class="!updateLoading ? '' : 'h-fit bg-white opacity-50 z-0 '" class=" flex flex-col gap-3">
      <div class="flex flex-col ">
        <h2 class="text-4xl  font-bold">Budget for {{ budgetInfo.budget.name }} </h2>
        <div class="flex flex-row gap-2 text-xl">{{ formatDate(budgetInfo.budget.dateFrom) }} -
          {{ formatDate(budgetInfo.budget.dateTo) }}
        </div>
      </div>
      <div class="flex flex-col gap-2">
      <!-- Аналитика и плановые доходы/расходы -->
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 items-start ">
        <!-- Блок Аналитики (25%) -->
        <div class="card p-4 shadow-lg rounded-lg col-span-2 h-fit">
          <h3 class="text-xl mb-4 font-bold">Analytics</h3>
          <div class="flex ">
            <div class="w-128">
              <Chart type="bar" :data="incomeExpenseChartData" class=""/>
            </div>
            <div class="h-fit">
<!--              <Chart type="pie" :data="incomeExpenseChartData" class="h-64"/>-->
            </div>
          </div>
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-5 items-center  justify-items-center mt-4">
            <div class="grid grid-cols-2 gap-5 items-center w-full">
              <div class="flex flex-col items-center font-bold ">
                <h4 class="text-xl font-bold text-green-500">Total Incomes:</h4>
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner w-full text-center">
                  +{{ formatAmount(budgetInfo.totalIncomes) }}
                  ₽
                </div>
                <!--              <p>Total Incomes</p>-->
              </div>
              <div class="flex flex-col items-center ">
                <h4 class="text-xl font-bold text-red-500">Total Expenses:</h4>
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner w-full text-center">
                  -{{ formatAmount(budgetInfo.totalExpenses) }}
                  ₽
                </div>
              </div>
              <div class="flex flex-col gap-2 items-center font-bold">
                <p class="font-bold ">Income at 10th:</p>
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner text-center  w-full px-2">
                  +{{ formatAmount(budgetInfo.chartData[0][0]) }} ₽
                </div>
              </div>
              <div class="flex flex-col gap-2 items-center">
                <p class="font-bold ">Income at 25th:</p>
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner text-center  w-full px-2">
                  +{{ formatAmount(budgetInfo.chartData[0][1]) }} ₽
                </div>
              </div>
              <div class="flex flex-col gap-2 items-center">
                <p class="font-bold ">Expenses at 10th:</p>
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner text-center   w-full px-2">
                  -{{ formatAmount(budgetInfo.chartData[1][0]) }} ₽
                </div>

              </div>
              <div class="flex flex-col gap-2 items-center">
                <p class="font-bold ">Expenses at 25th:</p>
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner text-center   w-full px-2">
                  -{{ formatAmount(budgetInfo.chartData[1][1]) }} ₽
                </div>
              </div>
              <div class="flex flex-col gap-2 items-center ">
                <p class="font-bold">Left for unplanned:</p>
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner w-full text-center">
                  {{ formatAmount(leftForUnplanned) }} ₽

                </div>
              </div>
              <div class="flex flex-col gap-2 items-center ">
                <p class="font-bold">Current spending:</p>
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner w-full text-center">
                  {{ formatAmount(leftForUnplanned) }} ₽
                </div>
              </div>


            </div>
          </div>
          <ProgressBar :value="value" class="mt-2"></ProgressBar>
          <div class="flex flex-col w-full items-end">

            <div class="flex flex-row items-end ">
              {{ formatAmount(leftForUnplanned) }} ₽
            </div>
          </div>
        </div>
        <div class="grid grid-cols-1 gap-4 row-span-3">
          <div class="card p-4 shadow-lg rounded-lg col-span-1  h-fit">
            <!-- Планируемые доходы -->
            <div>
              <div class="flex flex-row gap-4 items-center">
                <h3 class="text-xl font-bold text-green-500 mb-4 ">Planned Incomes</h3>
                <Button icon="pi pi-plus" rounded outlined size="small"/>
              </div>
              <div class="grid grid-cols-2 mb-2">
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner w-full text-center">
                  {{ formatAmount(budgetInfo.totalIncomes) }}
                  ₽
                </div>
                <div class="font-bold bg-gray-100  p-1 rounded-lg box-shadow-inner w-full text-center">
                  {{ formatAmount(totalIncomeLeftToGet) }}
                  ₽
                </div>
              </div>
              <ul class="space-y-2">

                <BudgetTransactionView v-for="transaction in budgetInfo.plannedIncomes" :transaction="transaction"/>

              </ul>

            </div>
          </div>
          <div class="card p-4 shadow-lg rounded-lg col-span-1  h-fit">
            <!-- Планируемые расходы -->
            <div class>
              <h3 class="text-xl font-bold text-red-500 mb-4">Planned Expenses</h3>
              <div class="grid grid-cols-2 mb-2">
                <div class="font-bold bg-gray-100 p-1 rounded-lg box-shadow-inner w-full text-center">
                  {{ formatAmount(budgetInfo.totalExpenses) }}
                  ₽
                </div>
                <div class="font-bold bg-gray-100  p-1 rounded-lg box-shadow-inner w-full text-center">
                  {{ formatAmount(totalExpenseLeftToSpend) }}
                  ₽
                </div>
              </div>
              <ul class="space-y-2">

                <BudgetTransactionView v-for="transaction in budgetInfo.plannedExpenses" :transaction="transaction"/>
              </ul>
            </div>
          </div>
        </div>

        <div class="row-span-1 col-span-2 h-fit">
          <h3 class="text-2xl font-bold mb-4">Unplanned Categories</h3>
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">

            <UnplannedCategoryView v-for="category in budgetInfo.unplannedCategories" :key="category.id"
                                   :category="category" :budget-id="budgetInfo.budget.id"
                                   @category-updated="updateBudgetCategory"
                                   class="p-4 shadow-lg rounded-lg bg-white flex justify-between items-center"/>

          </div>
        </div>
        <div class=" h-full  overflow-y-auto gap-4 flex-col row-span-2 col-span-2">
          <div class="flex flex-row ">
            <h3 class="text-2xl font-bold mb-4 ">Transactions List</h3>
          </div>
          <div class=" flex gap-2">
            <button v-for="categorySum in budgetInfo.transactionCategoriesSums" :key="categorySum.category.id"
                    class="rounded-full border p-1 bg-white border-gray-300 mb-2 px-2">
              <strong>{{ categorySum.category.name }}</strong>:
              {{ categorySum.sum }} ₽
            </button>
          </div>
          <div class="grid  grid-cols-1 gap-4 max-h-tlist overflow-y-auto">
            <BudgetTransactionView v-for="transaction in budgetInfo.transactions" :key="transaction.id"
                                   :transaction="transaction"
                                   @open-drawer="openDrawer"/>
          </div>
        </div>
      </div>


      </div>
    </div>
  </div>
</template>


<script setup lang="ts">
import {computed, onMounted, ref} from 'vue';
import Chart from 'primevue/chart';
import BudgetTransactionView from "@/components/budgets/BudgetTransactionView.vue";
import {CategoryType} from "@/models/Category";
import {getBudgetInfo, updateBudgetCategoryRequest} from "@/services/budgetsService";
import {BudgetInfo} from "@/models/Budget";
import {useRoute} from "vue-router";
import {formatAmount, formatDate} from "@/utils/utils";
import ProgressBar from "primevue/progressbar";
import ProgressSpinner from "primevue/progressspinner";
import UnplannedCategoryView from "@/components/budgets/UnplannedCategoryView.vue";
import {TransactionType} from "@/models/Transaction";
import Toast from "primevue/toast";
import Button from "primevue/button";

const loading = ref(true);
const updateLoading = ref(false);
const route = useRoute()

const budgetInfo = ref<BudgetInfo>();

const value = ref(50)

const leftForUnplanned = ref(0)

const drawerOpened = ref(false);
const transactionType = ref<TransactionType>()
const categoryType = ref<CategoryType>()


const totalIncomeLeftToGet = computed(() => {
  let totalIncomeLeftToGet = 0;
  budgetInfo.value?.plannedIncomes.forEach(i => {
    if (!i.isDone) {
      totalIncomeLeftToGet += i.amount
    }
  })
  return totalIncomeLeftToGet
})

const totalExpenseLeftToSpend = computed(() => {
  let totalExpenseLeftToSpend = 0;
  budgetInfo.value?.plannedExpenses.forEach(i => {
    if (!i.isDone) {
      totalExpenseLeftToSpend += i.amount
    }
  })
  return totalExpenseLeftToSpend
})
const fetchBudgetInfo = async () => {
  updateLoading.value = true
  console.log('Trying to get budget Info')
  budgetInfo.value = await getBudgetInfo(route.params.id);


  console.log(budgetInfo.value)
  console.log(budgetInfo.value?.chartData[0])
  incomeExpenseChartData.value = {
    labels: ['10.10', '25.10'],
    datasets: [
      {
        label: 'Income',
        backgroundColor: ['#2E8B57'],
        data: budgetInfo.value?.chartData[0],
      },
      {
        label: 'Expense',
        backgroundColor: ['#B22222'],
        data: budgetInfo.value?.chartData[1],
      },
    ],
  }
  leftForUnplanned.value =
      budgetInfo.value.chartData[0][0] +
      budgetInfo.value.chartData[0][1] -
      budgetInfo.value.chartData[1][0] -
      budgetInfo.value.chartData[1][1]

  updateLoading.value = false
}

const updateBudgetCategory = async (category) => {
  console.log(category)
  loading.value = true
  await updateBudgetCategoryRequest(budgetInfo.value.budget.id, category)
  budgetInfo.value = await getBudgetInfo(route.params.id)
  console.log(budgetInfo.value)
  console.log(budgetInfo.value?.chartData[0])
  incomeExpenseChartData.value = {
    labels: ['10.10', '25.10'],
    datasets: [
      {
        label: 'Income',
        backgroundColor: ['#2E8B57'],
        data: budgetInfo.value?.chartData[0],
      },
      {
        label: 'Expense',
        backgroundColor: ['#B22222'],
        data: budgetInfo.value?.chartData[1],
      },
    ],
  }
  leftForUnplanned.value =
      budgetInfo.value.chartData[0][0] +
      budgetInfo.value.chartData[0][1] -
      budgetInfo.value.chartData[1][0] -
      budgetInfo.value.chartData[1][1]
  loading.value = false

}

// Пример данных
const incomeExpenseChartData = ref();


onMounted(async () => {
  loading.value = true;
  try {
    await Promise.all([
      fetchBudgetInfo()
    ]);
  } catch (error) {
    console.error('Error during fetching data:', error);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
/* Добавляем стили для стилизации */
.card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.grid {
  gap: 1rem;
}

.max-h-tlist {
  max-height: 45dvh; /* Ограничение высоты списка */
}



.box-shadow-inner {
  box-shadow: inset 0 2px 4px 0 rgb(0 0 0 / 0.3);
}

</style>