<template>
  <v-dialog v-model="isOpen" max-width="500px" @close="closeModal">
    <v-card>
      <v-card-title>
        <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-text-field>
            </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 precisa ser válido'
              ]" required></v-text-field>
            </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-text-field>
            </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-text-field>
            </v-col>
            <v-col cols="12">
              <v-text-field v-model="localUser.phone" label="Telefone" type="tel" clearable :maxlength="15" required
                :rules="[
                  v => !!v || 'Telefone é obrigatório',
                  v => (v && v.length <= 15) || 'Telefone não pode ter mais de 15 caracteres'
                ]"></v-text-field>
            </v-col>

            <v-col cols="12">
              <v-text-field v-model="localUser.profile_image" label="URL da Imagem de Perfil" type="url"
                clearable></v-text-field>
            </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 color="blue-darken-1" @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';

const props = defineProps({
  isModalOpen: Boolean,
  isEditMode: Boolean,
  modalUser: Object
});

const emit = defineEmits(['update:isModalOpen', 'save']);
const userStore = useUserStore();

const isOpen = ref(props.isModalOpen);
const localUser = ref({
  id: props.modalUser?.id || null,
  username: props.modalUser?.username || '',
  email: props.modalUser?.email || '',
  password: '',
  birth_date: props.modalUser?.birth_date || '',
  phone: props.modalUser?.phone || '',
  profile_image: props.modalUser?.profile_image || ''
});

const isFormValid = computed(() => {
  const { username, email, password, birth_date, phone } = localUser.value;
  const isEmailValid = /.+@.+\..+/.test(email);

  return username &&
    email &&
    isEmailValid &&
    birth_date &&
    phone &&
    (props.isEditMode || password);
});

watch(() => props.isModalOpen, (newValue) => {
  isOpen.value = newValue;
  localUser.value = {
    id: props.modalUser?.id || null,
    username: props.modalUser?.username || '',
    email: props.modalUser?.email || '',
    password: '',
    birth_date: props.modalUser?.birth_date || '',
    phone: props.modalUser?.phone || '',
    profile_image: props.modalUser?.profile_image || ''
  };
});

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

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

const handleSave = async () => {
  if (!isFormValid.value) return;

  try {
    const userData = { ...localUser.value };
    if (props.isEditMode) {
      await userStore.updateUser(userData.id, userData);
    } else {
      await userStore.createUser(userData);
    }
    emit('save', userData);
    closeModal();
  } catch (error) {
    console.error('Erro ao salvar usuário:', error);
  }
};
</script>