<template>
  <Dialog :model-value="isOpen" @update:model-value="closeModal">
    <form @submit.prevent="onSubmit" class="mt-4">
      <div>
        <label for="list-name" class="block text-sm font-medium text-gray-700">{{
          $t('createListModal.listNameLabel')
          }}</label>
        <Input id="list-name" type="text" v-model="listName" required ref="listNameInput" class="mt-1 w-full" />
        <p v-if="formErrors.listName" class="mt-1 text-sm text-red-600">
          {{ formErrors.listName }}
        </p>
      </div>

      <div class="mt-4">
        <label for="list-description" class="block text-sm font-medium text-gray-700">{{
          $t('createListModal.descriptionLabel')
          }}</label>
        <textarea id="list-description" v-model="description" :rows="3"
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" />
      </div>

      <div v-if="props.groups && props.groups.length > 0" class="mt-4">
        <label for="list-group" class="block text-sm font-medium text-gray-700">{{
          $t('createListModal.groupLabel')
          }}</label>
        <select id="list-group" v-model="selectedGroupId"
          class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm">
          <option :value="SENTINEL_NO_GROUP">{{ $t('shared.none') }}</option>
          <option v-for="opt in props.groups" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
        </select>
      </div>

      <div class="mt-6 flex justify-end gap-x-2">
        <Button variant="outline" color="neutral" @click="closeModal" type="button">{{
          $t('createListModal.cancelButton') }}</Button>
        <Button type="submit" color="primary" :disabled="loading" @click="onSubmit">
          <Spinner v-if="loading" size="sm" class="mr-1" />
          {{ $t('createListModal.createButton') }}
        </Button>
      </div>
    </form>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, computed } from 'vue';
import { useVModel } from '@vueuse/core';
import { apiClient, API_ENDPOINTS } from '@/services/api';
import { useNotificationStore } from '@/stores/notifications';
import { Dialog, Input, Button, Spinner } from '@/components/ui';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

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 SENTINEL_NO_GROUP = 0;
const selectedGroupId = ref<number>(SENTINEL_NO_GROUP);
const loading = ref(false);
const formErrors = ref<{ listName?: string }>({});
const notificationStore = useNotificationStore();

const listNameInput = ref<any>(null);

const groupOptionsForSelect = computed(() => {
  return props.groups ? [{ label: t('shared.none'), value: SENTINEL_NO_GROUP }, ...props.groups] : [];
});

watch(isOpen, (newVal) => {
  if (newVal) {
    listName.value = '';
    description.value = '';
    if (props.groups && props.groups.length === 1) {
      selectedGroupId.value = props.groups[0].value;
    } else {
      selectedGroupId.value = SENTINEL_NO_GROUP;
    }
    formErrors.value = {};
    nextTick(() => {
      (listNameInput.value?.$el?.querySelector('input') as HTMLInputElement | undefined)?.focus();
    });
  }
});

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

const validateForm = () => {
  formErrors.value = {};
  if (!listName.value.trim()) {
    formErrors.value.listName = t('createListModal.errors.nameRequired');
  }
  return Object.keys(formErrors.value).length === 0;
};

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

    notificationStore.addNotification({
      message: t('createListModal.notifications.createSuccess'),
      type: 'success',
    });

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