<template>
  <h1>Compte</h1>
  <ul>
    <li>
      <p v-if="user.name">Nom : {{ user.name }}</p>
    </li>
    <li :class="{ 'is-editing': isEditingEmail }">
      <input
        v-if="isEditingEmail"
        type="email"
        v-model="email"
        id="username"
        placeholder="mail@exemple.com"
        autocomplete="username"
        class="w-full rounded-md border border-grey-200 px-16 py-12"
        :class="{ invalid: !isEmailValid }"
        required
      />
      <p v-else>Email : {{ user.email }}</p>
      <button
        v-if="isEditingEmail"
        class="btn | w-full"
        :class="'btn--' + emailBtn.status"
        :disabled="!isEmailValid"
        @click="updateEmail"
      >
        {{ emailBtn.text }}
      </button>
      <button v-else @click="isEditingEmail = true" class="btn | w-full">
        modifier
      </button>
    </li>
    <li :class="{ 'is-editing': isEditingEmail }">
      <input
        type="password"
        v-model="password"
        id="password"
        placeholder="Minimum 8 caractères"
        class="w-full rounded-md border border-grey-200 px-16 py-12"
        :class="{ invalid: password.length < 8 }"
        required
      />
      <input
        type="password"
        v-model="passwordConfirm"
        id="password-confirm"
        placeholder="Minimum 8 caractères"
        class="w-full rounded-md border border-grey-200 px-16 py-12"
        :class="{ invalid: !isPasswordConfirmed }"
        required
      />
      <button
        class="btn | w-full"
        :class="'btn--' + passwordBtn.status"
        :disabled="!isPasswordConfirmed ? true : undefined"
        @click="updatePassword"
      >
        {{ passwordBtn.text }}
      </button>
    </li>
    <li>
      <p>Client : {{ user.client.name }}</p>
    </li>
    <li v-if="user.hasOwnProperty('projects')">
      <p>Nombre de projets : {{ Object.values(user.projects).length }}</p>
    </li>
  </ul>
</template>
<script setup>
import { storeToRefs } from 'pinia';
import { useUserStore } from '../stores/user';
import { computed, ref, watch } from 'vue';

const { user } = storeToRefs(useUserStore());

// Email
const email = ref('');
const emailBtn = ref({
  text: 'mettre à jour',
  status: 'ready',
});
const isEditingEmail = ref(false);
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const isEmailValid = computed(() => {
  return emailRegex.test(email.value);
});
async function updateEmail() {
  emailBtn.value.text = 'en cours…';
  emailBtn.value.status = 'pending';

  const headers = {
    method: 'POST',
    body: JSON.stringify({
      email: email.value,
    }),
  };
  const response = await fetch('update-email.json', headers);
  const json = await response.json();

  if (json.status === 'success') {
    email.value = '';
    emailBtn.value.text = 'mise à jour réussie';
    emailBtn.value.status = 'succeed';

    setTimeout(() => {
      emailBtn.value.text = 'mettre à jour';
      emailBtn.value.status = 'ready';
    }, 1500);
  } else {
    console.log(json.message);
  }
}

// Password
const password = ref('');
const passwordBtn = ref({
  text: 'mettre à jour',
  status: 'ready',
});
const passwordConfirm = ref('');
const isPasswordConfirmed = computed(() => {
  return (
    passwordConfirm.value.length > 7 && passwordConfirm.value === password.value
  );
});
async function updatePassword() {
  passwordBtn.value.text = 'en cours…';
  passwordBtn.value.status = 'pending';

  const headers = {
    method: 'POST',
    body: JSON.stringify({
      password: password.value,
    }),
  };
  const response = await fetch('update-password.json', headers);
  const json = await response.json();

  if (json.status === 'success') {
    password.value = '';
    passwordConfirm.value = '';
    passwordBtn.value.text = 'mise à jour réussie';
    passwordBtn.value.status = 'succeed';

    setTimeout(() => {
      passwordBtn.value.text = 'mettre à jour';
      passwordBtn.value.status = 'ready';
    }, 1500);
  } else {
    console.log(json.message);
  }
}
</script>

<style scoped>
input.invalid:focus-visible {
  outline: 2px solid #ef8d8d;
}

.btn--pending {
  background-color: #ffdb88;
}

.btn--succeed {
  background-color: rgb(182, 211, 255);
}
</style>
