<template>
    <v-dialog v-model="isOpen" max-width="600px">
      <v-card class="pa-6 rounded-xl elevation-2 card-modal">
        <v-card-title class="text-h5 font-weight-bold pb-0">
          <span class="text-h5">{{ isEditMode ? 'Editar' : 'Adicionar' }} Ambiente</span>
        </v-card-title>
  
        <v-card-text>
          <v-container>
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="formData.name"
                  label="Nome do Ambiente"
                  required
                ></v-text-field>
              </v-col>
  
            <v-col cols="12">
                <v-textarea
                  v-model="formData.description"
                  label="Descrição"
                  rows="3"
                ></v-textarea>
            </v-col>
            
            </v-row>
          </v-container>
        </v-card-text>
  
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="error" variant="text" @click="close">Cancelar</v-btn>
          <v-btn  @click="save" class="text-white salvar-btn">Salvar</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </template>
  
  <script setup>
  import { ref, computed, watch, onMounted } from 'vue';
  import { useAuthStore } from '../../stores/auth';
  import { useSpaceStore } from '../../stores/spaces';
  
  const props = defineProps({
    modelValue: Boolean,
    ambiente: {
      type: Object,
      default: () => ({
        id: '',
        name: '',
        description: '',
      })
    },
    isEditMode: {
      type: Boolean,
      default: false
    }
  });
  
  const emit = defineEmits(['update:modelValue', 'save']);
  
  const authStore = useAuthStore();
  const spaceStore = useSpaceStore();
  //const selectedInstance = ref(authStore.currentInstance || null);
  
  const loading = ref(false);
  
  const formData = ref({
    id: '',
    name: '',
    description: '',
    ambiente_id: '',
    service_id: authStore.serviceId || 1,
    service_role_id: 5
  });
  
  const isOpen = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  });
  
  const resetForm = () => {
    formData.value = {
      id: '',
      name: '',
      description: '',
      service_id: authStore.serviceId || 1,
      service_role_id: 5
    };
  };
  
  const save = async () => {
    loading.value = true;
    try {
      const ambientePayload = {
        id: formData.value.id,
        name: formData.value.name,
        description: formData.value.description,
        service_id: formData.value.service_id || authStore.serviceId || 1,
        service_role_id: formData.value.service_role_id || 5
      };
  
      console.log('FINAL payload para envio:', JSON.stringify(ambientePayload, null, 2));
  
      if (props.isEditMode) {
        await spaceStore.updateSpace(ambientePayload.id, ambientePayload);
      } else {
        await spaceStore.createSpace(ambientePayload);
      }
  
      emit('save');
      close();
    } catch (error) {
      console.error('Erro ao salvar câmera:', error);
    } finally {
      loading.value = false;
    }
  };
  
  const close = () => {
    isOpen.value = false;
    resetForm();
  };
  
  /*onMounted(() => {
    fetchEnvironments();
  });
  */
  watch(
    () => props.modelValue,
    (val) => {
        if (val) {
        if (props.isEditMode && props.ambiente) {
            formData.value = {
            ...formData.value,
            ...props.ambiente,
            service_id: authStore.serviceId || 1,
            service_role_id: 5
            };
        } else {
            resetForm();
        }
        }
    }
    );
  </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>