<script setup lang="ts">
import Dialog from "primevue/dialog";
import Checkbox from "primevue/checkbox";
import Button from "primevue/button";
import InputText from "primevue/inputtext";
import FloatLabel from "primevue/floatlabel";
import DatePicker from "primevue/datepicker";
import {computed, onMounted, ref, watch} from "vue";
import {getMonthName} from "@/utils/utils";
import {Budget} from "@/models/Budget";
import {getCategories} from "@/services/categoryService";
import {useSpaceStore} from "@/stores/spaceStore";
import {createBudget} from "@/services/budgetsService";

const props = defineProps({
  opened: {
    type: Boolean,
    required: true
  }
})
const emits = defineEmits(['budget-created', 'close-modal'])
const createRecurrentPayments = ref<Boolean>(true)

const name = ref('')
const dateFrom = ref(new Date())
const dateTo = ref(new Date())

const budget = ref(new Budget())

const create = async () => {

  try {
    await createBudget(budget.value)
        .then((res) => budget.value = res)
        .catch((err) => console.log(err));
    emits("budget-created", budget.value, createRecurrentPayments.value);
  } catch (e) {
    console.error(e)
    throw e
  }

}
const categories = ref([])
const fetchCategories = async () => {
  await getCategories().then(res => categories.value = res.data)
}

const cancel = () => {
  emits("close-modal");
}

const resetForm = () => {
  budget.value.name = ''
  budget.value.dateTo = new Date();
  budget.value.dateFrom = new Date();
  budget.value.dateFrom.setDate(10)
  if (budget.value.dateFrom.getMonth() == 11) {
    budget.value.dateFrom.setMonth(0)
  } else {
    budget.value.dateFrom.setMonth(dateFrom.value.getMonth() + 1)
  }
  budget.value.dateTo.setDate(9)
  if (budget.value.dateTo.getMonth() == 10) {
    budget.value.dateTo.setMonth(0)
    budget.value.dateTo.setYear(dateTo.value.getFullYear() + 1)
  } else {
    budget.value.dateTo.setMonth(budget.value.dateTo.getMonth() + 2)
  }
  budget.value.name = getMonthName(budget.value.dateFrom.getMonth()) + ' ' + budget.value.dateFrom.getFullYear();
}
const spaceStore = useSpaceStore()
const selectedSpace = computed(() => spaceStore.space)

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

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


onMounted(() => {
  resetForm()
  if (selectedSpace.value) {
    fetchCategories()
  }
})

</script>

<template>
  <Dialog :visible="opened" modal header="Создать новый бюджет" :style="{ width: '25rem' }" @hide="cancel"
          @update:visible="cancel">
    <div class="flex flex-col gap-4 mt-1">
      <FloatLabel variant="on" class="w-full">
        <label for="name">Название</label>
        <InputText v-model="budget.name" id="name" class="w-full"/>
      </FloatLabel>
      <div class="flex flex-row gap-4">
        <FloatLabel variant="on">
          <label for="dateFrom">Дата начала</label>
          <DatePicker v-model="budget.dateFrom" id="dateFrom" dateFormat="dd.mm.yy"/>
        </FloatLabel>
        <FloatLabel variant="on">
          <label for="dateTo">Дата завершения</label>
          <DatePicker v-model="budget.dateTo" id="dateTo" dateFormat="dd.mm.yy"/>
        </FloatLabel>
      </div>
<!--      <div class="flex flex-row items-center min-w-fit gap-4">-->
<!--        <Checkbox v-model="createRecurrentPayments" binary/>-->
<!--        Создать ежемесячные платежи?-->
<!--      </div>-->
      <div v-if="categories.length ==0" class="text-red-500 font-bold">Сперва лучше создать категории</div>
      <div class="flex flex-row gap-2 justify-end items-center">
        <Button label="Создать" severity="success" icon="pi pi-save" @click="create"/>
        <Button label="Отмена" severity="secondary" icon="pi pi-times-circle" @click="cancel"/>
      </div>
    </div>
  </Dialog>

</template>

<style scoped>

</style>