<template>
  <v-dialog v-model="isOpen" max-width="500px" @close="closeModal">
    <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 Usuário' : 'Adicionar Novo Usuário' }}</span>
      </v-card-title>
      <v-card-text>
        <v-container>
          <v-row>
            <v-col cols="12">
              <v-text-field v-model="localUser.username" label="Usuário *" clearable
                :rules="[v => !!v || 'Usuário é obrigatório']" required />
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="localUser.email" label="Email *" type="email" clearable
                :rules="[v => !!v || 'Email é obrigatório', v => /.+@.+\..+/.test(v) || 'Email inválido']" required />
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="localUser.password" label="Senha *" type="password" clearable
                :rules="[v => !(!isEditMode && !v) || 'Senha é obrigatória']" :disabled="isEditMode" required />
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="localUser.birth_date" label="Data de Nascimento *" type="date" clearable
                :rules="[v => !!v || 'Data de nascimento é obrigatória']" required />
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="localUser.phone" label="Telefone *" type="tel" clearable
                :rules="[v => !!v || 'Telefone é obrigatório', v => /^[0-9]+$/.test(v) || 'Apenas números permitidos']" />
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="localUser.profile_image" label="URL da Imagem de Perfil" type="url" clearable />
            </v-col>
          </v-row>
        </v-container>
      </v-card-text>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn text color="blue-darken-1" @click="closeModal">Cancelar</v-btn>
        <v-btn text class="text-white salvar-btn" @click="handleSave" :loading="userStore.loading" :disabled="!isFormValid">
          Salvar
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>
<script setup>
import { ref, watch, computed } from 'vue';
import { useUserStore } from '../../stores/users';
import { useAuthStore } from '../../stores/auth';

const props = defineProps({
  isModalOpen: Boolean,
  isEditMode: Boolean,
  modalUser: Object
});
const emit = defineEmits(['update:isModalOpen', 'save', 'user-updated']);
const userStore = useUserStore();
const authStore = useAuthStore();

console.log('service intance id',authStore.service_instance_id);
const isOpen = ref(false);
const localUser = ref({
  id: null,
  username: '',
  email: '',
  password: '',
  birth_date: '',
  phone: '',
  profile_image: '',
  parent_id: authStore.userId,
  service_instance_id: authStore.service_instance_id || 2,
});
// Resetar dados ao abrir para novo usuário
const resetLocalUser = () => {
  localUser.value = {
    id: null,
    username: '',
    email: '',
    password: '',
    birth_date: '',
    phone: '',
    profile_image: '',
    parent_id: authStore.userId,
  service_instance_id: authStore.service_instance_id,

  };
};
// Sincroniza `isOpen` com `props.isModalOpen`
watch(() => props.isModalOpen, (newValue) => {
  isOpen.value = newValue;
  if (newValue) {
    if (props.isEditMode && props.modalUser) {
      loadUserData();
    } else {
      resetLocalUser(); // <- limpa os dados para novo usuário
    }
  }
});
// Atualiza `props.isModalOpen` quando o modal é fechado
watch(isOpen, (newValue) => {
  if (!newValue) {
    emit('update:isModalOpen', false);
  }
});
const loadUserData = async () => {
  try {
    const fullUserData = await userStore.fetchUserById(props.modalUser.id);
    if (fullUserData) {
      localUser.value = {
        id: fullUserData.user.id || null,
        username: fullUserData.user.username || '',
        email: fullUserData.user.email || '',
        password: '',
        birth_date: fullUserData.user.birth_date
          ? new Date(fullUserData.user.birth_date).toISOString().split('T')[0]
          : '',
        phone: fullUserData.user.phone || '',
        profile_image: fullUserData.user.profile_image || '',
        parent_id: authStore.userId,
        service_instance_id: authStore.service_instance_id,
      };
    }
    console.log('Enviando userData:', fullUserData);
  } catch (error) {
    console.error('Erro ao carregar dados do usuário:', error);
  }
};
const isFormValid = computed(() => {
  const { username, email, password, birth_date, phone } = localUser.value;
  const isEmailValid = /.+@.+\..+/.test(email);
  const isPhoneValid = /^[0-9]+$/.test(phone);
  return username &&
    email &&
    isEmailValid &&
    birth_date &&
    phone &&
    isPhoneValid &&
    (props.isEditMode || password);
});
const closeModal = () => {
  isOpen.value = false;
};
const handleSave = async () => {
  if (!isFormValid.value) return;
  try {
    const userData = {
      phone: String(localUser.value.phone || '').replace(/\D/g, ''),
      birth_date: new Date(localUser.value.birth_date).toISOString(),
      service_instance_id: authStore.service_instance_id,
      parent_id: authStore.userId,
      ...localUser.value,
      
    };
    if (!props.isEditMode) {
      delete userData.id;
    }
    if (props.isEditMode) {
      await userStore.updateUser(userData.id, userData);
    } else {
      await userStore.createUser(userData);
    }
    emit('user-updated');
    closeModal();
  } catch (error) {
    console.error('Erro ao salvar usuário:', error);
  }
};
</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>