<template>
  <q-dialog v-model="isOpen" persistent>
    <q-card style="min-width: 350px">
      <q-card-section class="row items-center">
        <div class="text-h6">Create New List</div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-card-section>
        <q-form @submit="onSubmit" class="q-gutter-md">
          <q-input
            v-model="listName"
            label="List Name"
            :rules="[(val) => !!val || 'Name is required']"
            outlined
          />

          <q-input v-model="description" label="Description" type="textarea" outlined />

          <q-select
            v-model="selectedGroup"
            :options="groups"
            label="Associate with Group (Optional)"
            outlined
            clearable
          />

          <div class="row justify-end q-mt-md">
            <q-btn label="Cancel" color="grey" flat v-close-popup />
            <q-btn label="Create" type="submit" color="primary" class="q-ml-sm" />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useQuasar } from 'quasar';
import { api } from 'src/boot/axios';

const $q = useQuasar();

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

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

const isOpen = ref(props.modelValue);
const listName = ref('');
const description = ref('');
const selectedGroup = ref(null);

// Watch for modelValue changes
watch(
  () => props.modelValue,
  (newVal) => {
    isOpen.value = newVal;
  },
);

// Watch for isOpen changes
watch(isOpen, (newVal) => {
  emit('update:modelValue', newVal);
});

const onSubmit = async () => {
  try {
    const response = await api.post('/api/v1/lists', {
      name: listName.value,
      description: description.value,
      groupId: selectedGroup.value?.value,
    });

    $q.notify({
      type: 'positive',
      message: 'List created successfully',
    });

    // Reset form
    listName.value = '';
    description.value = '';
    selectedGroup.value = null;

    // Close modal and emit created event
    isOpen.value = false;
    emit('created');
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: 'Failed to create list',
    });
  }
};
</script>
