<template>
    <v-dialog v-model="isOpen" max-width="500px">
      <v-card class="pa-6 rounded-xl elevation-2 card-modal">
        <v-card-title class="text-h5 font-weight-bold pb-0">{{ isEditMode ? 'Editar Ambiente' : 'Adicionar Ambiente' }}</v-card-title>
        <v-card-text>
          <!-- Formulário -->
          <v-text-field v-model="localSpace.name" label="Nome do Ambiente" outlined dense />
          <v-textarea v-model="localSpace.description" label="Descrição" outlined dense />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="closeModal">Cancelar</v-btn>
          <v-btn text color="primary" @click="handleSave" :disabled="!isFormValid" class="text-white salvar-btn">Salvar</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </template>
  
  <script setup>
  import { ref, watch, computed } from 'vue';
  import { useAuthStore } from '../../stores/auth';
  
  const props = defineProps({
    isModalOpen: Boolean,
    isEditMode: Boolean,
    modalSpace: Object,
  });
  
  const emit = defineEmits(['update:isModalOpen', 'save']);
  
  const isOpen = ref(props.isModalOpen);
  const localSpace = ref({ ...props.modalSpace });
  const authStore = useAuthStore();
  const selectedInstance = ref(authStore.currentInstance || null);
  
  watch(() => props.isModalOpen, (newValue) => {
    isOpen.value = newValue;
    localSpace.value.service_instance_id = selectedInstance;
    localSpace.value = { ...props.modalSpace };
  });
  
  watch(isOpen, (newValue) => {
    emit('update:isModalOpen', newValue);
  });
  
  const closeModal = () => {
    isOpen.value = false;
  };
  
  const isFormValid = computed(() => {
    return localSpace.value.name.trim() !== '';
  });
  
  const handleSave = () => {
    if (isFormValid.value) {
      localSpace.value.service_instance_id = selectedInstance;
      emit('save', localSpace.value);
      closeModal();
    }
  };
  </script>
  
  <style scoped>
  .card-modal {
    background-color: #ffffff;
    border-radius: 16px;
  }
  
  .salvar-btn {
    background: linear-gradient(to right, #6b4eff, #2eb6ff);
    border-radius: 999px;
    text-transform: none;
    font-weight: 500;
  }
  </style>