<template>
  <LoadingView v-if="loading"/>
  <div v-else class="p-4 bg-gray-100 h-full flex  flex-col gap-4 ">
    <!-- Заголовок -->
    <div class="flex flex-row gap-4 items-center">
      <h2 class="text-4xl font-bold">Бюджеты</h2>
      <Button label="+ Создать" @click="creationOpened=true" size="small"/>
      <BudgetCreationView :opened="creationOpened" @budget-created="creationSuccessShow"
                          @close-modal="creationOpened=false"/>
      <StatusView :show="creationSuccessModal" :is-error="false" :message="'Бюджет создан!'"/>
    </div>
    <!-- Плитка с бюджетами -->
    <div v-if="!selectedSpace" class="flex w-full h-full items-center justify-center">
      <p>Сперва нужно выбрать Пространство.
        <button class="text-blue-500 hover:underline" @click="router.push('/spaces').then((res) => router.go(0))">Перейти</button>
      </p>
    </div>
    <div v-else-if="budgetInfos.length==0" class="flex w-full h-full items-center justify-center">
      <p>Кажется, в этом пространстве еще нет бюджетов
        <button class="text-blue-500 hover:underline" @click="creationOpened=true">создайте один.</button>
      </p>
    </div>
    <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
      <!-- Будущие и текущие бюджеты -->
      <ConfirmDialog/>
      <Toast/>

      <div v-for="budget in budgetInfos" :key="budget.id" class="p-4 shadow-lg rounded-lg bg-white"
           :class="budget.dateTo < new Date() ? 'bg-gray-100 opacity-60' : ''">
        <div class="flex flex-row justify-between gap-4">
          <div class="flex flex-col justify-between gap-5">
            <div class="text-xl font-bold ">{{ budget.name }}</div>
            <div class="text-sm text-gray-600 ">
              {{ formatDate(budget.dateFrom) }} - {{ formatDate(budget.dateTo) }}
            </div>

          </div>
          <div class="flex flex-col justify-between gap-4">
            <router-link :to="'/budgets/'+budget.id">
              <i class="pi pi-arrow-circle-right text-green-500" style="font-size: 1.5rem;"/>
            </router-link>
            <button @click="deleteBudget(budget)"><i class="pi pi-trash" style="color:red; font-size: 1.2rem"/></button>
          </div>
        </div>

      </div>


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

<script setup lang="ts">
import {computed, onMounted, ref, watch} from 'vue';
import {Budget, BudgetInfo} from "@/models/Budget";
import {createBudget, deleteBudgetRequest, getBudgetInfos} from "@/services/budgetsService";
import {formatDate} from "@/utils/utils";
import LoadingView from "@/components/LoadingView.vue";
import Button from "primevue/button";
import ConfirmDialog from "primevue/confirmdialog";
import BudgetCreationView from "@/components/budgets/BudgetCreationView.vue";
import StatusView from "@/components/StatusView.vue";
import {useConfirm} from "primevue/useconfirm";
import {useToast} from "primevue/usetoast";
import Toast from "primevue/toast";
import router from "@/router";
import {useSpaceStore} from "@/stores/spaceStore";

const confirm = useConfirm();
const toast = useToast();
const loading = ref(false)
const budgetInfos = ref<BudgetInfo[]>([])
const creationOpened = ref(false)
const creationSuccessModal = ref(false)

const creationSuccessShow = async (budget, createRecurrentPayments) => {
  try {
    await createBudget(budget, createRecurrentPayments)
    budgetInfos.value = await getBudgetInfos()
    toast.add({severity: 'success', summary: 'Успешно!', detail: 'Бюджет создан!', life: 3000});
    creationOpened.value = false
  } catch (error) {
    console.log(error.response.data["message"])
    toast.add({severity: "error", summary: "Бюджет не создан", detail: error.response.data["message"], life: 3000});
  }
  // creationSuccessModal.value = true
  // setTimeout(() => {
  //       creationSuccessModal.value = false
  //     }
  //     , 1000)
}

const deleteBudget = async (budget: Budget) => {

  confirm.require({
    message: `Вы действительно хотите удалить бюджет ${budget.name} ?`,
    header: 'Удаление бюджета',
    icon: 'pi pi-info-circle',
    rejectLabel: 'Отмена',
    rejectProps: {
      label: 'Отмена',
      severity: 'secondary',
      outlined: true
    },
    acceptProps: {
      label: 'Удалить',
      severity: 'danger'
    },
    accept: async () => {
      try {
        await deleteBudgetRequest(budget.id)
        // showToast("Confirmed")
        budgetInfos.value = await getBudgetInfos()
        toast.add({severity: 'success', summary: 'Успешно!', detail: 'Бюджет удален!', life: 3000});
      } catch (e: Error) {
        toast.add({severity: 'error', summary: "Ошибка при удалении", detail: e.message, life: 3000});
      }
    },
    reject: () => {
      toast.add({severity: 'info', summary: 'Отменено', detail: 'Вы отменили удаление', life: 3000});
    }
  });
}
const spaceStore = useSpaceStore()
const selectedSpace = computed(() => spaceStore.space)

watch(
    () => selectedSpace.value,
    async (newValue, oldValue) => {

      if (newValue != oldValue || !oldValue) {
        try {
          loading.value = true;
          // Если выбранный space изменился, получаем новую информацию о бюджете
          await getBudgetInfos().then((result) => {
            budgetInfos.value = result
            loading.value = false;
          })
        } catch (error) {
          console.error('Error fetching budget infos:', error);
        }
      }
    }
);

onMounted(async () => {
  if (selectedSpace.value) {
    loading.value = true;
    budgetInfos.value = await getBudgetInfos()
    loading.value = false;
  }
})
</script>

<style scoped>
/* Стили для плиток и общего вида */
.grid {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
}

@media (min-width: 640px) {
  .grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 1024px) {
  .grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
</style>
