<template>
    <form @submit.prevent="handleSubmit">
        <div class="form-group">
            <label for="category-name">Category Name</label>
            <input type="text" id="category-name" v-model="categoryName" required />
        </div>
        <div class="form-actions">
            <button type="submit" :disabled="loading">
                {{ isEditing ? 'Update' : 'Create' }}
            </button>
            <button type="button" @click="emit('cancel')" :disabled="loading">
                Cancel
            </button>
        </div>
    </form>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, onMounted, computed } from 'vue';
import type { Category } from '../stores/categoryStore';

const props = defineProps<{
    category?: Category | null;
    loading: boolean;
}>();

const emit = defineEmits<{
    (e: 'submit', data: { name: string }): void;
    (e: 'cancel'): void;
}>();

const categoryName = ref('');

const isEditing = computed(() => !!props.category);

onMounted(() => {
    if (props.category) {
        categoryName.value = props.category.name;
    }
});

const handleSubmit = () => {
    if (categoryName.value.trim()) {
        emit('submit', { name: categoryName.value.trim() });
    }
};
</script>