<!-- Modal Component (ServiceInstanceModal.vue) -->
<template>
    <v-dialog 
      :model-value="modelValue" 
      @update:model-value="$emit('update:modelValue')" 
      max-width="500px"
    >
  
      <v-card>
        <v-card-title>{{ isEditMode ? 'Editar Instância' : 'Adicionar Instância' }}
        </v-card-title>
        <v-card-text>
          <v-form ref="form" v-model="isFormValid">
            <v-text-field
              v-model="localInstance.name"
              label="Nome da Instância"
              :rules="nameRules"
              required
              outlined
              dense
            />
            <v-textarea
              v-model="localInstance.description"
              label="Descrição da Instância"
              outlined
              dense
            />
          </v-form>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text color="red" @click="closeModal">Cancelar</v-btn>
          <v-btn
            text
            color="primary"
            @click="handleSave"
            :disabled="!isFormValid"
          >
            {{ isEditMode ? 'Atualizar' : 'Salvar' }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </template>
  
  <script setup>
  import { ref, watch } from 'vue';
  import { useAuthStore } from '../../stores/auth';
  const props = defineProps({
    modelValue: {
      type: Boolean,
      required: true
    },
    isEditMode: {
      type: Boolean,
      default: false
    },
    instance: {
      type: Object,
      required: true
    }
  });
  
  const authStore = useAuthStore();
  
  const emit = defineEmits(['update:modelValue', 'save']);
  
  // Form state
  const form = ref(null);
  const isFormValid = ref(false);
  const localInstance = ref({ ...props.instance });
  
  // Validation rules
  const nameRules = [
    v => !!v || 'Nome é obrigatório',
    v => v.length >= 3 || 'Nome deve ter pelo menos 3 caracteres'
  ];
  
  // Watch for changes in props
  watch(() => props.instance, (newValue) => {
    localInstance.value = { ...newValue };
  }, { deep: true });
  
  // Methods
  const closeModal = () => {
    emit('update:modelValue', false);
    form.value?.reset();
  };
  
  const handleSave = () => {
    if (form.value?.validate()) {
      emit('save', { ...localInstance.value, service_id: Number(authStore.serviceId) });
      closeModal();
  
      // Limpando dados após o salvar
      localInstance.value = {
        id: null,
        name: '',
        description: ''
      };
    }
  };
  
  </script>