<template>
  <v-dialog v-model="isOpen" max-width="900px" @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 font-weight-bold pb-0">{{ isEditMode ? 'Editar Usuário' : 'Adicionar Novo Usuário' }}</span>
      </v-card-title>
      <v-card-text>
        <v-container>
          <v-row>
            
            <!-- Dados Básicos -->
            <v-col cols="12">
              <h3 class="text-body-1 text-grey-darken-1 pb-4">Dados Básicos</h3>
            </v-col>
            <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" md="4">
              <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" md="4">
              <v-text-field v-model="localUser.cpf" label="CPF" clearable />
            </v-col>
            <v-col cols="12" md="4">
              <v-text-field v-model="localUser.pis" label="PIS" clearable />
            </v-col>
            <v-col cols="12" md="4">
              <v-text-field v-model="localUser.rg" label="RG" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <v-text-field v-model="localUser.codigo_interno" label="Código Interno" clearable />
            </v-col>
            <!--Contato-->
            <v-col cols="12">
              <h3 class="text-body-1 text-grey-darken-1 pb-4">Contato</h3>
            </v-col>
            <v-col cols="12" md="6">
              <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" md="6">
              <v-text-field v-model="localUser.email_secundario" label="E-mail Secundário" type="email" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <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" md="6">
              <v-text-field v-model="localUser.telefone_secundario" label="Telefone Secundário" type="tel" clearable />
            </v-col>

            <!--Endereço-->
            <v-col cols="12">
              <h3 class="text-body-1 text-grey-darken-1 pb-4">Endereço</h3>
            </v-col>
            <v-col cols="12" md="4">
              <v-text-field v-model="localUser.cep" label="CEP" clearable />
            </v-col>
            <v-col cols="12" md="8">
              <v-text-field v-model="localUser.rua" label="Rua" clearable />
            </v-col>
            <v-col cols="12" md="4">
              <v-text-field v-model="localUser.numero" label="Número" clearable />
            </v-col>
            <v-col cols="12" md="4">
              <v-text-field v-model="localUser.bairro" label="Bairro" clearable />
            </v-col>
            <v-col cols="12" md="4">
              <v-text-field v-model="localUser.complemento" label="Complemento" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <v-text-field v-model="localUser.estado" label="Estado" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <v-text-field v-model="localUser.cidade" label="Cidade" clearable />
            </v-col>

            <!-- Informações do trabalho -->
            <v-col cols="12">
              <h3 class="text-body-1 text-grey-darken-1 pb-4">Informações do Trabalho</h3>
            </v-col>
            <v-col cols="12" md="6">
              <v-select v-model="localUser.empresa" :items="empresas" label="Empresa" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <v-select v-model="localUser.cargo" :items="cargos" :disabled="true" label="Cargo" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <v-select v-model="localUser.setor" :items="setores" :disabled="true" label="Setor" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <v-select v-model="localUser.escala" :items="escalas" label="Escala" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <v-select v-model="localUser.feriado" :items="feriados" label="Feriado" clearable />
            </v-col>
            <v-col cols="12" md="6">
              <v-select v-model="localUser.fuso_horario" :items="fusosHorarios" label="Fuso Horário" clearable />
            </v-col>

            <!--Login usuario-->
            
            
            <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.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 {
    console.log('Carregando dados do usuário:', props.modalUser);
    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>