<template>
    <div>
        <h1>Category Management</h1>
        <CategoryForm v-if="showForm" :category="selectedCategory" :loading="loading" @submit="handleFormSubmit"
            @cancel="cancelForm" />
        <div v-else>
            <button @click="showCreateForm">Create Category</button>
            <ul v-if="categories.length">
                <li v-for="category in categories" :key="category.id">
                    {{ category.name }}
                    <button @click="showEditForm(category)">Edit</button>
                    <button @click="handleDelete(category.id)" :disabled="loading">Delete</button>
                </li>
            </ul>
            <p v-else-if="!loading">No categories found.</p>
        </div>
        <p v-if="loading">Loading...</p>
        <p v-if="error">{{ error }}</p>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useCategoryStore, type Category } from '../stores/categoryStore';
import CategoryForm from '../components/CategoryForm.vue';
import { storeToRefs } from 'pinia';

const categoryStore = useCategoryStore();
const { categories, loading, error } = storeToRefs(categoryStore);

const showForm = ref(false);
const selectedCategory = ref<Category | null>(null);

onMounted(() => {
    categoryStore.fetchCategories();
});

const showCreateForm = () => {
    selectedCategory.value = null;
    showForm.value = true;
};

const showEditForm = (category: Category) => {
    selectedCategory.value = category;
    showForm.value = true;
};

const cancelForm = () => {
    showForm.value = false;
    selectedCategory.value = null;
};

const handleFormSubmit = async (data: { name: string }) => {
    if (selectedCategory.value) {
        await categoryStore.updateCategory(selectedCategory.value.id, data);
    } else {
        await categoryStore.createCategory(data);
    }
    cancelForm();
};

const handleDelete = async (id: number) => {
    await categoryStore.deleteCategory(id);
};
</script>