<template>
  <section-wrapper class="bg-background-3 pb-12">
    <section-container mobile-padding class="max-w-container">
      <div class="rounded-xl bg-white px-12 py-8">
        <h2 class="text-primary mb-10 text-[1.563rem] font-bold">
          Mes informations personnelles
        </h2>
        <ProgressBar
          v-if="fetching"
          mode="indeterminate"
          class="mb-10"
          style="height: 6px"
        ></ProgressBar>
        <Message severity="error" v-if="error">{{ error }}</Message>

        <Message :sticky="false" life="3000" severity="success" v-if="success"
          >{{ success }}
        </Message>
        <form v-if="meData" @submit.prevent="update">
          <div class="grid-cols-2 gap-x-10 md:grid">
            <FormField
              class="mb-2"
              name="firstname"
              label="Prénom"
              :errors="validationErrors"
            >
              <div class="p-input-icon-right">
                <i class="pi pi-pencil" />
                <InputText
                  v-model="meData.firstname"
                  type="text"
                  placeholder="Votre prénom"
                  :class="`w-full ${
                    validationErrors.firstname ? 'p-invalid' : ''
                  }`"
                  :disabled="loading"
                />
              </div>
            </FormField>
            <FormField
              class="mb-2"
              name="lastname"
              label="Nom"
              :errors="validationErrors"
            >
              <div class="p-input-icon-right">
                <i class="pi pi-pencil" />
                <InputText
                  v-model="meData.lastname"
                  type="text"
                  placeholder="Votre nom"
                  :class="`w-full ${
                    validationErrors.lastname ? 'p-invalid' : ''
                  }`"
                  :disabled="loading"
                />
              </div>
            </FormField>
            <FormField
              class="col-span-2 mb-2"
              name="email"
              label="Email"
              :errors="validationErrors"
            >
              <div class="p-input-icon-right">
                <i class="pi pi-envelope" />
                <InputText
                  v-model="meData.email"
                  type="email"
                  placeholder="Votre adresse email"
                  :class="`w-full ${validationErrors.email ? 'p-invalid' : ''}`"
                  :disabled="loading"
                />
              </div>
            </FormField>

            <FormField
              class="mb-2"
              name="password"
              label="Mot de passe"
              :errors="validationErrors"
            >
              <div class="p-input-icon-right">
                <i class="pi pi-lock" />
                <InputText
                  v-model="meData.password"
                  type="password"
                  placeholder="Changer votre mot de passe"
                  :class="`w-full ${
                    validationErrors.password ? 'p-invalid' : ''
                  }`"
                  :disabled="loading"
                />
              </div>
            </FormField>

            <FormField
              class="mb-2"
              name="password_confirmation"
              label="Confirmation mot de passe"
              :errors="validationErrors"
            >
              <div class="p-input-icon-right">
                <i class="pi pi-lock" />
                <InputText
                  v-model="meData.password_confirmation"
                  type="password"
                  placeholder="Confirmer votre mot de passe"
                  :class="`w-full ${
                    validationErrors.password_confirmation ? 'p-invalid' : ''
                  }`"
                  :disabled="loading"
                />
              </div>
            </FormField>
          </div>
          <div class="flex justify-center py-10">
            <rounded-button
              :loading="loading"
              type="submit"
              design="1"
              class="px-[5rem]"
              >{{ loading ? "Mise à jour en cours..." : "Mettre à jour" }}
            </rounded-button>
          </div>
        </form>

        <div
          v-else
          class="flex items-center justify-center pb-[5rem] pt-[5rem]"
        >
          <ProgressSpinner
            r
            style="width: 250px; height: 250px"
            :pt="{
              spinner: { style: { animationDuration: '0.5s' } },
              circle: {
                style: {
                  stroke: 'var(--primary-500)',

                  strokeWidth: 0.3,
                  animation: 'none',
                },
              },
            }"
          />
        </div>
      </div>
    </section-container>
  </section-wrapper>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { useAuthStore } from "../store/auth";
import { cloneDeep } from "lodash";
import { useUtils } from "../composables/utils";

const { convertToSuccess, errorHandler } = useUtils();

const authStore = useAuthStore();

const meData = ref(null);

const loading = ref(false);
const fetching = ref(false);

const success = ref(null);

const error = ref(null);
const validationErrors = ref({});

const { $toast, $listen, $unListen } = useNuxtApp();

const update = async () => {
  loading.value = true;
  error.value = null;
  success.value = null;
  validationErrors.value = {};
  const toastId = $toast.loading("Mise à jour en cours...");
  try {
    const me = await authStore.updateMe(meData.value);
    meData.value = me;

    convertToSuccess(toastId, "Vos informations ont été mises à jour");

    success.value = "Vos informations ont été mises à jour";
  } catch (e) {
    errorHandler(e, error, validationErrors, toastId);
  } finally {
    loading.value = false;
  }
};

const fetchMe = () => {
  fetching.value = true;
  error.value = null;

  return authStore
    .fetchMe()
    .then(() => {
      meData.value = cloneDeep(authStore.me);
    })
    .catch((err) => {
      errorHandler(err, error);
    })
    .finally(() => {
      fetching.value = false;
    });
};

onMounted(async () => {
  const me = await authStore.fetchMe();

  meData.value = cloneDeep(me);

  $listen("refresh-all", fetchMe);
});

onBeforeUnmount(() => {
  $unListen("refresh-all", fetchMe);
});
</script>
