<template>
  <VModal :model-value="isOpen" @update:model-value="closeModal" title="Create New List">
    <template #default>
      <form @submit.prevent="onSubmit">
        <VFormField label="List Name" :error-message="formErrors.listName">
          <VInput type="text" v-model="listName" required ref="listNameInput" />
        </VFormField>

        <VFormField label="Description">
          <VTextarea v-model="description" rows="3" />
        </VFormField>

        <VFormField label="Associate with Group (Optional)" v-if="props.groups && props.groups.length > 0">
          <VSelect v-model="selectedGroupId" :options="groupOptionsForSelect" placeholder="None" />
        </VFormField>
        <!-- Form submission is handled by button in footer slot -->
      </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, computed } from 'vue';
import { useVModel } from '@vueuse/core'; // onClickOutside removed
import { apiClient, API_ENDPOINTS } from '@/config/api'; // Assuming this path is correct
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 VTextarea from '@/components/valerie/VTextarea.vue';
import VSelect from '@/components/valerie/VSelect.vue';
import VButton from '@/components/valerie/VButton.vue';
import VSpinner from '@/components/valerie/VSpinner.vue';

const props = defineProps<{
  modelValue: boolean;
  groups?: Array<{ label: string; value: number }>;
}>();

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

const isOpen = useVModel(props, 'modelValue', emit);
const listName = ref('');
const description = ref('');
const selectedGroupId = ref<number | null>(null); // Store only the ID
const loading = ref(false);
const formErrors = ref<{ listName?: string }>({});
const notificationStore = useNotificationStore();

const listNameInput = ref<InstanceType<typeof VInput> | null>(null);
// const modalContainerRef = ref<HTMLElement | null>(null); // Removed

const groupOptionsForSelect = computed(() => {
  const options = props.groups ? props.groups.map(g => ({ label: g.label, value: g.value })) : [];
  // VSelect expects placeholder to be passed as a prop, not as an option for empty value usually
  // However, if 'None' is a valid selectable option representing null, this is okay.
  // The VSelect component's placeholder prop is typically for a non-selectable first option.
  // Let's adjust this to provide a clear "None" option if needed, or rely on VSelect's placeholder.
  // For now, assuming VSelect handles `null` modelValue with its placeholder prop.
  // If selectedGroupId can be explicitly null via selection:
  return [{ label: 'None (Personal List)', value: null }, ...options];
});


watch(isOpen, (newVal) => {
  if (newVal) {
    // Reset form when opening
    listName.value = '';
    description.value = '';
    selectedGroupId.value = null; // Default to 'None' or personal list
    formErrors.value = {};
    nextTick(() => {
      listNameInput.value?.focus?.();
    });
  }
});

// onClickOutside removed, VModal handles backdrop clicks

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

const validateForm = () => {
  formErrors.value = {};
  if (!listName.value.trim()) {
    formErrors.value.listName = 'Name is required';
  }
  return Object.keys(formErrors.value).length === 0;
};

const onSubmit = async () => {
  if (!validateForm()) {
    return;
  }
  loading.value = true;
  try {
    const response = await apiClient.post(API_ENDPOINTS.LISTS.BASE, {
      name: listName.value,
      description: description.value,
      group_id: selectedGroupId.value,
    });

    notificationStore.addNotification({ message: 'List created successfully', type: 'success' });

    emit('created', response.data);
    closeModal();
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Failed to create list';
    notificationStore.addNotification({ message, type: 'error' });
    console.error(message, error);
  } finally {
    loading.value = false;
  }
};
</script>

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

.ml-2 {
  margin-left: 0.5rem;
  /* from Valerie UI utilities */
}
</style>