<template>
  <div v-if="loading">

  </div>
  <div v-else class="flex flex-col bg-gray-100 dark:bg-gray-800 h-screen p-4">
    <!-- Заголовок и кнопка добавления категории -->
    <div class="flex flex-row justify-between  bg-gray-100">
      <h2 class="text-5xl font-bold">Categories</h2>
      <Button label="Add Category" icon="pi pi-plus" class="p-button-success" @click="openCreateDialog(null)"/>
    </div>

    <!-- Поле для поиска -->
    <div class="my-4 w-full">
      <span class="p-input-icon-left flex flex-row gap-2  items-center ">
        <i class="pi pi-search"></i>
        <InputText v-model="searchTerm" placeholder="Search categories..." class="w-full"/>
      </span>
    </div>

    <!-- Переключатель категорий (доходы/расходы) -->
    <div class="card flex sm:hidden justify-center mb-4">
      <SelectButton v-model="selectedCategoryType" :options="categoryTypes" optionLabel="name"
                    aria-labelledby="category-switch"/>
    </div>

    <!-- Список категорий с прокруткой для больших экранов -->
    <div class="flex">
      <div class="hidden sm:grid grid-cols-2 gap-x-10 w-full h-full justify-items-center overflow-y-auto">
        <!-- Категории доходов -->
        <div class="grid  h-full w-full  min-w-fit overflow-y-auto">
          <div class=" gap-4    ">
            <div class="flex flex-row gap-2 ">
              <h3 class="text-2xl">Income Categories</h3>
              <Button icon="pi pi-plus" rounded outlined class="p-button-success" @click="openCreateDialog('INCOME')"/>
            </div>
          </div>
          <div class="  overflow-y-auto   mt-2 space-y-2 px-2">
            <CategoryListItem
                class=""
                v-for="category in filteredIncomeCategories"
                :key="category.id"
                :category="category"
                v-bind="category"
                @open-edit="openEdit"
                @delete-category="deleteCat"
            />
          </div>
        </div>

        <!-- Категории расходов -->
        <div class="grid h-full w-full  min-w-fit overflow-y-auto">
          <div class=" gap-4 justify-between  ">
            <div class="flex flex-row gap-2">
              <h3 class="text-2xl">Expense Categories</h3>
              <Button icon="pi pi-plus" rounded outlined class="p-button-success !hover:bg-green-600"
                      @click="openCreateDialog('EXPENSE')"/>
            </div>
          </div>
          <div class=" overflow-y-auto  pb-10 mt-2 space-y-2 px-2">
            <CategoryListItem
                v-for="category in filteredExpenseCategories"
                :key="category.id"
                :category="category"
                v-bind="category"
                @open-edit="openEdit"
                @delete-category="deleteCat"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- Для маленьких экранов -->
    <div class="flex sm:hidden flex-wrap rounded w-full">
      <CategoryListItem
          v-for="category in filteredCategories"
          :key="category.id"
          :category="category"
          v-bind="category"
          class="mt-2"
          @open-edit="openEdit"
          @delete-category="deleteCat"
      />
    </div>

    <CreateCategoryModal
        :show="isDialogVisible"
        :categoryTypes="categoryTypes"
        :selectedCategoryType="selectedCategoryType"
        :category="editingCategory"
        @saveCategory="saveCategory"
        @close-modal="closeCreateDialog"
        @update:visible="closeCreateDialog"
    />
  </div>
</template>

<script lang="ts">
import {computed, nextTick, onMounted, ref, watch} from 'vue';
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import SelectButton from 'primevue/selectbutton';
import CreateCategoryModal from './CreateCategoryModal.vue';
import CategoryListItem from '@/components/settings/categories/CategoryListItem.vue';
import {Category, CategoryType} from '@/models/Category';
import {
  createCategory,
  deleteCategory,
  getCategories,
  getCategoryTypes,
  updateCategory
} from "@/services/categoryService";

export default {
  components: {
    Button,
    InputText,
    SelectButton,
    CreateCategoryModal,
    CategoryListItem,
  },
  setup() {
    const loading = ref(true);
    const entireCategories = ref<Category[]>([]);
    const expenseCategories = ref<Category[]>([]);
    const incomeCategories = ref<Category[]>([]);
    const editingCategory = ref<Category | null>(null);
    const isDialogVisible = ref(false);

    const fetchCategories = async () => {
      loading.value = true
      try {
        const response = await getCategories();
        entireCategories.value = response.data
        expenseCategories.value = response.data.filter((category: Category) => category.type.code === 'EXPENSE');
        incomeCategories.value = response.data.filter((category: Category) => category.type.code === 'INCOME');
      } catch (error) {
        console.error('Error fetching categories:', error);
      }
      loading.value = false
    };

    const categoryTypes = ref<CategoryType[]>([]);
    const selectedCategoryType = ref<CategoryType | null>(null);
    const fetchCategoryTypes = async () => {
      loading.value = true
      try {
        const response = await getCategoryTypes();
        categoryTypes.value = response.data;
        selectedCategoryType.value = categoryTypes.value.find((category: CategoryType) => category.code === 'EXPENSE');
      } catch (error) {
        console.error('Error fetching category types:', error);
      }
      loading.value = false
    };

    const searchTerm = ref('');

    const filteredExpenseCategories = computed(() =>
        expenseCategories.value.filter(category =>
            category.name.toLowerCase().includes(searchTerm.value.toLowerCase())
        )
    );

    const filteredIncomeCategories = computed(() =>
        incomeCategories.value.filter(category =>
            category.name.toLowerCase().includes(searchTerm.value.toLowerCase())
        )
    );

    const filteredCategories = computed(() => {
      if (selectedCategoryType.value?.code === 'EXPENSE') {
        return filteredExpenseCategories.value;
      } else {
        return filteredIncomeCategories.value;
      }
    });

    const openCreateDialog = (categoryType: CategoryType | null = null) => {
      if (categoryType) {
        selectedCategoryType.value = categoryType;
      } else if (editingCategory.value) {
        selectedCategoryType.value = editingCategory.value.type;
      } else {
        selectedCategoryType.value = categoryTypes.value.find(category => category.code === 'EXPENSE');
      }
      isDialogVisible.value = true;
    };

    const closeCreateDialog = () => {
      isDialogVisible.value = false;
      editingCategory.value = null; // Сбрасываем категорию при закрытии
    };

    const saveCategory = async (newCategory: Category) => {
      if (newCategory.id) {
        await updateCategory(newCategory.id, newCategory);
      } else {
        await createCategory(newCategory);
      }
      await fetchCategories()
      closeCreateDialog();
    };

    const deleteCat = async (categoryId: number) => {
      await deleteCategory(categoryId);
      await fetchCategories();
    }

    const openEdit = (category: Category) => {
      editingCategory.value = category;
      nextTick(() => {
        openCreateDialog(category.type); // Обновляем форму для редактирования
      });
    };

    watch(editingCategory, (newCategory) => {
      if (newCategory) {
        selectedCategoryType.value = newCategory.type; // Обновляем тип при редактировании
      }
    });

    onMounted(async () => {
      await fetchCategories();
      await fetchCategoryTypes();
      loading.value = false;
    });

    return {
      expenseCategories,
      incomeCategories,
      selectedCategoryType,
      categoryTypes,
      searchTerm,
      filteredExpenseCategories,
      filteredIncomeCategories,
      filteredCategories,
      isDialogVisible,
      openCreateDialog,
      closeCreateDialog,
      saveCategory,
      deleteCat,
      openEdit,
      editingCategory,
      loading,
    };
  },
};
</script>


<style scoped>
/* Прокрутка для категорий */
.overflow-y-auto {
  max-height: 80vh; /* Ограничение высоты для появления прокрутки */
}
</style>
