﻿<template>
  <div>
    <div class="flex flex-col items-center min-w-[300px] sm:min-w-[400px] md:min-w-[500px] lg:min-w-[700px] m-4">
      <h1 class="text-center text-2xl font-bold mb-5">Inscription</h1>
      <div class="w-full h-0.5 mt-4 mb-4" :style="{ backgroundColor: '#A30E79' }"></div>
      <div class="w-full">
        <v-text-field
            v-model="userName"
            label="Username"
            variant="outlined"
            dense
            prepend-inner-icon="mdi-account"
            color="transparent"
            class="text-black mb-4"
            :rules="[userNameRule]"
        ></v-text-field>
        <div class="flex flex-wrap justify-between gap-4 mb-4">
          <v-text-field
              v-model="firstName"
              label="Prénom"
              variant="outlined"
              dense
              prepend-inner-icon="mdi-account"
              color="transparent"
              class="text-black flex-grow min-w-[250px]"
          ></v-text-field>
          <v-text-field
              v-model="lastName"
              label="Nom"
              variant="outlined"
              dense
              prepend-inner-icon="mdi-account"
              color="transparent"
              class="text-black flex-grow min-w-[250px]"
          ></v-text-field>
        </div>
        <v-text-field
            v-model="emailAddress"
            label="Courriel"
            variant="outlined"
            dense
            prepend-inner-icon="mdi-email"
            color="transparent"
            class="text-black mb-4"
            :error="emailError"
            :error-messages="emailErrorMessage"
            :rules="[emailRule]"
        ></v-text-field>
        <v-text-field
            v-model="password"
            label="Mot de passe"
            :type="showPassword ? 'text' : 'password'"
            variant="outlined"
            dense
            prepend-inner-icon="mdi-lock"
            append-inner-icon="mdi-eye"
            @click:append-inner="togglePasswordVisibility"
            color="transparent"
            class="text-black mb-4"
            :rules="[passwordRule]"
        ></v-text-field>
        <v-text-field
            v-model="confirmPassword"
            label="Confirmer mot de passe"
            :type="showPassword ? 'text' : 'password'"
            variant="outlined"
            dense
            prepend-inner-icon="mdi-lock"
            append-inner-icon="mdi-eye"
            @click:append-inner="togglePasswordVisibility"
            color="transparent"
            class="text-black mb-4"
            :rules="[validatePasswordRule]"
        ></v-text-field>
        <v-btn
            class="w-full text-center text-white"
            :style="{ backgroundColor: '#A30E79' }"
            @click="validateForm"
        >
          Créer
        </v-btn>
      </div>
    </div>

    <!-- Modal for errors -->
    <v-dialog v-model="errorDialog" max-width="500px">
      <v-card>
        <v-card-title class="headline">Erreur</v-card-title>
        <v-card-text>{{ errorMessage }}</v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="primary" text @click="closeErrorDialog">Fermer</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useClient } from "@/plugins/api.js";

const router = useRouter();
const client = useClient();

const firstName = ref('');
const lastName = ref('');
const emailAddress = ref('');
const password = ref('');
const confirmPassword = ref('');
const userName = ref('');
const showPassword = ref(false);
const errorDialog = ref(false);
const errorMessage = ref('');
const emailError = ref(false);
const emailErrorMessage = ref('');

// Validation regex
const userNameRegex = /^[a-zA-Z0-9]+$/;
const emailRegex = /.+@.+\..+/;
const passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{6,}$/;

// Messages d'erreur
const ERROR_MESSAGES = {
  INVALID_EMAIL: 'E-mail doit être valide',
  PASSWORD_MISMATCH: 'Les mots de passe ne correspondent pas.',
  WEAK_PASSWORD: 'Doit contenir 6 caractères, un chiffre, une lettre minuscule, majuscule et un caractère non-alphanumérique.',
  GENERIC_ERROR: 'Une erreur est survenue. Veuillez réessayer.',
  INVALID_USERNAME: "Le nom d'utilisateur ne doit contenir que des lettres sans accent et/ou des chiffres.",
};

function togglePasswordVisibility() {
  showPassword.value = !showPassword.value;
}

function passwordRule(password) {
  if (passwordRegex.test(password)) {
    return true;
  }
  return ERROR_MESSAGES.WEAK_PASSWORD;
}

function validatePasswordRule(validatePassword) {
  if (password.value === validatePassword) {
    return true;
  }
  return ERROR_MESSAGES.PASSWORD_MISMATCH;
}

function emailRule(email) {
  if (emailRegex.test(email)) {
    return true;
  }
  return ERROR_MESSAGES.INVALID_EMAIL
}

function userNameRule(userName) {
  if (userNameRegex.test(userName)){
    return true
  }
  return ERROR_MESSAGES.INVALID_USERNAME;
}

function validateForm() {
  emailError.value = false;
  emailErrorMessage.value = '';

  if (!emailRegex.test(emailAddress.value)) {
    emailError.value = true;
    emailErrorMessage.value = ERROR_MESSAGES.INVALID_EMAIL;
    return;
  }
  
  if (!userNameRegex.test(userName.value)){
    showErrorDialog(ERROR_MESSAGES.INVALID_EMAIL);
    return;
  }

  if (password.value !== confirmPassword.value) {
    showErrorDialog(ERROR_MESSAGES.PASSWORD_MISMATCH);
    return;
  }

  if (!passwordRegex.test(password.value)) {
    showErrorDialog(ERROR_MESSAGES.WEAK_PASSWORD);
    return;
  }

  createUser();
}

function showErrorDialog(message) {
  errorMessage.value = message;
  errorDialog.value = true;
}

function closeErrorDialog() {
  errorDialog.value = false;
}

async function createUser() {
  try {
    const userInformation = {
      FirstName: firstName.value,
      LastName: lastName.value,
      EmailAddress: emailAddress.value,
      UserName: userName.value,
      Password: password.value,
    };

    await client.post('/api/Users', userInformation);
    router.push('/login');
  } catch (error) {
    console.log(error);
    showErrorDialog(ERROR_MESSAGES.GENERIC_ERROR);
  }
}
</script>
