<template>
  <v-dialog v-model="isOpen" max-width="800px" @close="closeModal">
    <v-card class="pa-6 rounded-xl elevation-2">
      <v-card-title class="text-h5 font-weight-bold pb-0">
        <span>{{ isEditMode ? 'Editar Colaborador' : 'Adicionar Colaborador' }}</span>
      </v-card-title>
      <v-card-subtitle class="mb-4">Preencha os dados do novo colaborador e clique em adicionar.</v-card-subtitle>

      <v-card-text>
        <v-container>
          <v-row>
            <v-col cols="12" md="6">
              <label class="field-label">Nome Completo</label>
              <v-text-field v-model="localUser.username" hide-details clearable required />
            </v-col>
            <v-col cols="12" md="6">
              <label class="field-label">E-mail</label>
              <v-text-field v-model="localUser.email" hide-details clearable required />
            </v-col>
            <v-col cols="12" md="6">
              <label class="field-label">Cargo</label>
              <v-text-field v-model="localUser.cargo" hide-details clearable />
            </v-col>
            <v-col cols="12" md="6">
              <label class="field-label">Departamento</label>
              <v-text-field v-model="localUser.department" hide-details clearable />
            </v-col>
            <v-col cols="12" md="6">
              <label class="field-label">Data de Admissão</label>
              <v-text-field v-model="localUser.admission_date" type="date" hide-details clearable required />
            </v-col>
            <v-col cols="12" md="6">
              <label class="field-label">Status</label>
              <v-select
                v-model="localUser.status"
                :items="['Ativo', 'Inativo']"
                hide-details
                clearable
              />
            </v-col>
            <v-col cols="12">
              <label class="field-label">Escala de Trabalho</label>
              <v-select
                v-model="localUser.escala"
                :items="['Comercial (8h–17h)', 'Plantão 12x36', 'Noturno (22h–6h)']"
                hide-details
                clearable
              />
            </v-col>
          </v-row>
        </v-container>
      </v-card-text>

      <v-card-actions class="button-actions">
        <v-spacer></v-spacer>

        <v-btn
          variant="outlined"
          class="cancel-btn"
          @click="closeModal"
        >
          Cancelar
        </v-btn>

        <v-btn
          :disabled="!isFormValid"
          class="add-btn"
          @click="handleSave"
        >
          Adicionar
        </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', 'user-updated']);

const userStore = useUserStore();
const authStore = useAuthStore();

const isOpen = ref(false);
const localUser = ref({
  id: null,
  username: '',
  email: '',
  admission_date: '',
  cargo: '',
  department: '',
  status: 'Ativo',
  escala: '',
  parent_id: authStore.userId,
  service_instance_id: authStore.service_instance_id,
});

const resetLocalUser = () => {
  localUser.value = {
    id: null,
    username: '',
    email: '',
    admission_date: '',
    cargo: '',
    department: '',
    status: 'Ativo',
    escala: '',
    parent_id: authStore.userId,
    service_instance_id: authStore.service_instance_id,
  };
};

watch(() => props.isModalOpen, async (newValue) => {
  isOpen.value = newValue;
  if (newValue) {
    if (props.isEditMode && props.modalUser && props.modalUser.id) {
      try {
        const fullUser = await userStore.fetchUserById(props.modalUser.id);
        if (fullUser && fullUser.user) {
          localUser.value = {
            id: fullUser.user.id,
            username: fullUser.user.username || '',
            email: fullUser.user.email || '',
            admission_date: fullUser.user.admission_date
            ? new Date(fullUser.user.admission_date).toISOString().split('T')[0]
            : '',
            cargo: fullUser.user.cargo || '',
            department: fullUser.user.department || '',
            status: fullUser.user.status || 'Ativo',
            escala: fullUser.user.escala || '',
            parent_id: fullUser.user.parent_id || authStore.userId,
            service_instance_id: fullUser.user.service_instance_id || authStore.service_instance_id,
          };
        }
      } catch (error) {
        console.error('Erro ao buscar dados do usuário:', error);
        resetLocalUser();
      }
    } else {
      resetLocalUser();
    }
  }
});

watch(isOpen, (newValue) => {
  if (!newValue) emit('update:isModalOpen', false);
});

const isFormValid = computed(() => {
  return (
    !!localUser.value.username &&
    !!localUser.value.email &&
    !!localUser.value.admission_date
  );
});

const closeModal = () => {
  isOpen.value = false;
};

const handleSave = async () => {
  if (!isFormValid.value) return;
  try {
    const userData = { ...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>
.v-card-subtitle {
  color: #64748b;
  font-size: 14px;
}
.field-label {
  display: block;
  font-size: 18px;
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 4px;
  margin-left: 4px;
}
.button-actions {
  padding-top: 16px;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn {
  border-radius: 8px;
  font-weight: 500;
  padding: 0 20px;
  height: 44px; 
  color: #1e293b;
  border: 1px solid #d1d5db;
  background-color: #fff;
}

.add-btn {
  border-radius: 8px;
  font-weight: 500;
  padding: 0 20px;
  height: 44px; 
  color: white;
  background-color: #2563eb;
}

</style>

