<template>
    <v-dialog v-model="isOpen" max-width="600px">
      <v-card>
        <v-card-title>
          <span class="text-h5">{{ isEditMode ? 'Editar' : 'Adicionar' }} Câmera</span>
        </v-card-title>
  
        <v-card-text>
          <v-container>
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="formData.name"
                  label="Nome da Câmera"
                  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-col cols="12">
                <v-text-field
                  v-model="formData.connection_url"
                  label="URL de Conexão"
                  required
                ></v-text-field>
              </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 color="primary" @click="save">Salvar</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </template>
  
  <script setup>
  import { ref, computed, watch } from 'vue';
  import { useAuthStore } from '../../stores/auth';
  
  const props = defineProps({
    modelValue: Boolean,
    camera: {
      type: Object,
      default: () => ({
        name: '',
        description: '',
        connection_url: ''
      })
    },
    spaceId: {
      type: [Number, String],
      required: true
    },
    isEditMode: {
      type: Boolean,
      default: false
    }
  });
  
  const emit = defineEmits(['update:modelValue', 'save']);
  const authStore = useAuthStore();
  const selectedInstance = ref(authStore.currentInstance || null);
  
  const formData = ref({
    name: '',
    description: '',
    connection_url: ''
  });
  
  const isOpen = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  });
  
  watch(() => props.modelValue, (val) => {
    if (val && props.isEditMode) {
      formData.value = { ...props.camera };
    }
  });
  
  const close = () => {
    isOpen.value = false;
    resetForm();
  };
  
  const save = () => {
    const cameraData = {
      ...formData.value,
      space_id: props.spaceId,
      service_instance_id: selectedInstance.value?.id
    };
    emit('save', cameraData);
    close();
  };
  
  const resetForm = () => {
    formData.value = {
      name: '',
      description: '',
      connection_url: ''
    };
  };
  </script>
  