<template>
    <VModal :model-value="isOpen" @update:model-value="closeModal" title="Create New Group">
        <template #default>
            <form @submit.prevent="onSubmit">
                <VFormField label="Group Name" :error-message="formError ?? undefined">
                    <VInput type="text" v-model="groupName" required ref="groupNameInput" />
                </VFormField>
            </form>
        </template>
        <template #footer>
            <VButton variant="neutral" @click="closeModal" type="button">Cancel</VButton>
            <VButton type="submit" variant="primary" :disabled="loading" @click="onSubmit" class="ml-2">
                <VSpinner v-if="loading" size="sm" />
                Create
            </VButton>
        </template>
    </VModal>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
import { useVModel } from '@vueuse/core';
import { apiClient, API_ENDPOINTS } from '@/services/api';
import { useNotificationStore } from '@/stores/notifications';
import VModal from '@/components/valerie/VModal.vue';
import VFormField from '@/components/valerie/VFormField.vue';
import VInput from '@/components/valerie/VInput.vue';
import VButton from '@/components/valerie/VButton.vue';
import VSpinner from '@/components/valerie/VSpinner.vue';

const props = defineProps<{
    modelValue: boolean;
}>();

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void;
    (e: 'created', newGroup: any): void;
}>();

const isOpen = useVModel(props, 'modelValue', emit);
const groupName = ref('');
const loading = ref(false);
const formError = ref<string | null>(null);
const notificationStore = useNotificationStore();
const groupNameInput = ref<InstanceType<typeof VInput> | null>(null);

watch(isOpen, (newVal) => {
    if (newVal) {
        groupName.value = '';
        formError.value = null;
        nextTick(() => {
            // groupNameInput.value?.focus?.();
        });
    }
});

const closeModal = () => {
    isOpen.value = false;
};

const validateForm = () => {
    formError.value = null;
    if (!groupName.value.trim()) {
        formError.value = 'Name is required';
        return false;
    }
    return true;
};

const onSubmit = async () => {
    if (!validateForm()) {
        return;
    }
    loading.value = true;
    try {
        const payload = { name: groupName.value };
        const response = await apiClient.post(API_ENDPOINTS.GROUPS.BASE, payload);
        notificationStore.addNotification({ message: 'Group created successfully', type: 'success' });
        emit('created', response.data);
        closeModal();
    } catch (error: any) {
        const message = error?.response?.data?.detail || (error instanceof Error ? error.message : 'Failed to create group');
        formError.value = message;
        notificationStore.addNotification({ message, type: 'error' });
        console.error(message, error);
    } finally {
        loading.value = false;
    }
};
</script>

<style>
.form-error-text {
    color: var(--danger);
    font-size: 0.85rem;
    margin-top: 0.25rem;
}

.ml-2 {
    margin-left: 0.5rem;
}
</style>