<template>
  <v-dialog
    v-model="open"
    width="700"
  >
    <div class="py-12 px-3 flex flex-col gap-10 bg-white">
      <img
        :src="logo.url_small"
        alt="logo Search And Stay"
        style="max-width: 200px"
        format="webp"
        quality="80"
      />
      <div class="flex flex-col mt-4">
        <h2>Validate your email</h2>
        <p class="pt-2">
          Enter the 6-digit code we’ve sent to your email to verify your
          identity and access your account. This step keeps your Search and Stay
          login secure.
        </p>
      </div>

      <v-row class="py-5 justify-center" tag="form" @submit.prevent="onSubmit">
        <v-col cols="12">
          <v-text-field
            v-model.trim="code"
            :error="$v.code.$dirty && $v.code.$error"
            :error-messages="getErrors($v.code)"
            hide-details="auto"
            label="Code"
            placeholder="Code *"
            required
            type="number"
            variant="outlined"
            @blur="$v.code.$touch()"
          />
        </v-col>
        <v-col cols="12" md="4">
          <v-btn
            :loading="loading"
            block
            color="primary"
            height="50"
            type="submit"
          >
            {{ loading ? "Loading..." : "Send Code" }}
          </v-btn>
        </v-col>
        <v-col cols="12" class="mt-5">
          <v-alert
            :color="messageAlert.messageType"
            :model-value="messageAlert.showAlert"
            class="w-100"
            closable
            @click:close="messageAlert.dismissedAlert"
          >
            <span v-html="messageAlert.message"></span>
          </v-alert>
        </v-col>
      </v-row>
    </div>
  </v-dialog>
</template>

<script setup>
const { useVuelidate } = Vuelidate;
const { minLength, required } = VuelidateValidators;

const logo = Vue.ref({
  url_small: "https://assets.searchandstay.com/midias/60a34d82cc193_small.png",
});
const store = window.useValidationEmail();
const userStore = window.useUserStore();
const loading = Vue.ref(false);
const code = Vue.ref("");
const messageAlert = Vue.ref({
  showAlert: false,
  message: "",
  messageType: "",
});
const emit = defineEmits(["validated", "close"]);

const rules = {
  code: {
    required,
    minLength: minLength(6),
  },
};
const $v = useVuelidate(rules, { code });

const open = Vue.computed({
  get() {
    return store.modalValidationEmail;
  },
  set(value) {
    store.modalValidationEmail = value
  },
});

const onSubmit = async () => {
  $v.value.code.$touch();
  if ($v.value.code.$invalid) return;

  try {
    loading.value = true;
    await axios.post("/guest/two_authentication/validate_token", {
      guests: { code: code.value },
    });
    await userStore.setSyncUser();

    store.modalValidationEmail = false
    emit("validated");
  } catch (error) {
    console.error("ERROR", error);
    messageAlert.value.showAlert = true;
    messageAlert.value.message =
      (error.response?.data?.message?.length &&
        error.response?.data?.message[0]) ||
      error.response?.data?.data ||
      "An error occurred";
    messageAlert.value.messageType = "error";
  } finally {
    loading.value = false;
  }
};

const getErrors = ($v) => {
  if ($v.$dirty && $v.$errors?.length)
    return $v.$errors.map((e) => {
      switch (e.$validator) {
        case "sameAs":
          return "Passwords do not match";
        default:
          return e.$message;
      }
    });
  else return [];
};
</script>
