<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' }} 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.url"
                label="URL de Conexão"
                required
              ></v-text-field>
            </v-col>

            <v-col cols="12">
              <v-select
                v-model="formData.status"
                :items="['Ativo', 'Inativo']"
                label="Status"
                required
              ></v-select>
            </v-col>

            <v-col cols="12">
              <v-select
                v-model="formData.ambiente_id"
                :items="environmentOptions"
                label="Ambiente"
                item-value="value"
                item-title="title"
                required
              ></v-select>
            </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="salvar-btn text-white">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';
import { cameraService } from '../../services/camera';


const props = defineProps({
  modelValue: Boolean,
  camera: {
    type: Object,
    default: () => ({
      id: '',
      name: '',
      description: '',
      url: '',
      status: '',
      ambiente_id: ''
    })
  },
  isEditMode: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue', 'save']);

const authStore = useAuthStore();
const spaceStore = useSpaceStore();
console.log('id chefe:',authStore.userId)
const isOpen = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

const environmentOptions = ref([]);
const loading = ref(false);

const formData = ref({
  id: '',
  name: '',
  description: '',
  url: '',
  status: 'Ativo',
  ambiente_id: '',
  service_id: authStore.serviceId || 1,
  service_instance_id: authStore.service_instance_id || 2,
  service_role_id: 5
});

const fetchEnvironments = async () => {
  try {
    const ambientes = await spaceStore.getAmbientes();
    environmentOptions.value = ambientes.map(env => ({
      title: env.name,
      value: env.id
    }));
  } catch (error) {
    console.error("Erro ao buscar ambientes:", error);
  }
};

const resetForm = () => {
  formData.value = {
    id: '',
    name: '',
    description: '',
    url: '',
    status: 'Ativo',
    ambiente_id: '',
    service_id: authStore.serviceId || 1,
    service_instance_id: authStore.service_instance_id || 2,
    service_role_id: 5
  };
};

const save = async () => {
  loading.value = true;
  try {
    const cameraPayload = {
      ...formData.value,
      service_instance_id: authStore.service_instance_id || 2 // reforça o uso correto
    };

    console.log('FINAL payload para envio:', JSON.stringify(cameraPayload, null, 2));

    if (props.isEditMode) {
      await cameraService.updateCamera(cameraPayload.id, cameraPayload);
    } else {
      await cameraService.createCamera(cameraPayload);
    }

    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.camera) {
        formData.value = {
          ...formData.value,
          ...props.camera,
          service_instance_id: authStore.service_instance_id || 2
        };
      } 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>