<template>
    <Dialog v-model="isOpen" class="max-w-md w-full p-6 bg-white rounded-lg dark:bg-neutral-800">
        <Heading :level="3" class="mb-4">{{ t('createGroupModal.title', 'Create New Household') }}</Heading>
        <form @submit.prevent="onSubmit">
            <div class="mb-4">
                <label class="block text-sm font-medium mb-1" for="groupNameInput">{{ t('createGroupModal.nameLabel',
                    'Group Name') }}</label>
                <Input id="groupNameInput" v-model="groupName"
                    :placeholder="t('createGroupModal.namePlaceholder', 'e.g. My Household')" required />
                <Alert v-if="formError" type="error" :message="formError" class="mt-1" />
            </div>
            <div class="flex justify-end gap-2 mt-6">
                <Button variant="ghost" color="neutral" type="button" @click="closeModal">{{ t('shared.cancel',
                    'Cancel') }}</Button>
                <Button type="submit" :disabled="loading">
                    <Spinner v-if="loading" size="sm" class="mr-1" />
                    {{ t('createGroupModal.create', 'Create') }}
                </Button>
            </div>
        </form>
    </Dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
import { useVModel } from '@vueuse/core';
import { useI18n } from 'vue-i18n';
import { apiClient, API_ENDPOINTS } from '@/services/api';
import { useNotificationStore } from '@/stores/notifications';
import Dialog from '@/components/ui/Dialog.vue';
import Input from '@/components/ui/Input.vue';
import Button from '@/components/ui/Button.vue';
import Spinner from '@/components/ui/Spinner.vue';
import Heading from '@/components/ui/Heading.vue';
import Alert from '@/components/ui/Alert.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 { t } = useI18n();
const groupNameInput = ref<InstanceType<typeof Input> | null>(null);

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

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

function validateForm() {
    formError.value = null;
    if (!groupName.value.trim()) {
        formError.value = t('createGroupModal.nameRequired', '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: t('createGroupModal.success', '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 scoped></style>