<template>
  <v-container
    :style="{
      maxWidth:
        loginOrSignUp === 'login' ? '400px !important' : '800px !important',
    }"
  >
    <v-sheet class="pa-4" rounded="lg">
      <form v-if="loginOrSignUp === 'login'" @submit.prevent="login.submit()">
        <v-defaults-provider :defaults="defaults">
          <v-alert
            v-if="login.error && login.error.data"
            class="mb-4"
            type="error"
          >
            {{ login.error.data }}
          </v-alert>

          <v-text-field
            v-model="login.params.email"
            label="E-mail"
            type="email"
            :disabled="userStore.getLogin?.id"
          />
          <!-- v-bind="{
						  errorMessages: login.errors('login.email'),
						  hideDetails: !login.errors('login.email'),
						}" -->

          <v-text-field
            v-model="login.params.password"
            label="Password"
            :disabled="userStore.getLogin?.id"
            v-bind="{
              type: password.view ? 'text' : 'password',
              appendInnerIcon: password.view ? 'mdi-eye-off' : 'mdi-eye',
            }"
            @click:appendInner="password.view = !password.view"
          />
          <!-- errorMessages: login.errors('login.password'),
						  hideDetails: !login.errors('login.password'), -->

          <div class="d-flex justify-content-center">
            <v-btn
              v-bind="{
                type: 'submit',
                size: 'large',
                color: 'primary',
                height: 50,
                width: 200,
                loading: login.loading,
                disabled: login.loading,
              }"
            >
              {{ userStore.getLogin?.id ? "Next" : "Login" }}
            </v-btn>
          </div>

          <v-divider class="my-3">or</v-divider>

          <div class="mt-1 mb-4">
            <LoginSocialMedias />
          </div>

          <v-divider class="my-3" />

          <div class="d-flex align-center justify-center">
            Need an account?
            <v-btn
              class="p-0 ml-2"
              size="small"
              variant="text"
              @click="changeLoginOrSignUp('sign-up')"
            >
              Sign Up
            </v-btn>
          </div>

          <v-divider class="my-3" />
          <div class="text-center">
            <v-btn
              class="p-0"
              size="small"
              variant="text"
              @click="changeLoginOrSignUp('forgot-password')"
            >
              Forgot password
            </v-btn>
          </div>
        </v-defaults-provider>
      </form>

      <div v-else-if="loginOrSignUp === 'sign-up'">
        <v-alert v-if="errorSignUp.error" class="mb-4" type="error"
          >{{ errorSignUp.message }}
        </v-alert>

        <sign-up
          :loading="loadingSignUp"
          variantSubmit="elevated"
          @submit="(v) => signUpUser(v)"
        />
        <v-divider class="my-5" />
        <v-btn
          class="p-0 d-block mx-auto"
          size="small"
          variant="text"
          @click="changeLoginOrSignUp('login')"
        >
          Back
        </v-btn>
      </div>

      <div v-else-if="loginOrSignUp === 'forgot-password'">
        <span class="d-block text-center mb-5">
          You will receive a recovery link in your email
        </span>

        <forgot-password />
        <v-divider class="my-5" />
        <v-btn
          class="p-0 d-block mx-auto"
          size="small"
          variant="text"
          @click="changeLoginOrSignUp('login')"
        >
          Back
        </v-btn>
      </div>

      <!--			<v-col-->
      <!--				cols="12"-->
      <!--				v-if="!!userStore.getUser"-->
      <!--				class="mt-7 d-flex justify-end"-->
      <!--			>-->
      <!--				<v-col cols="6">-->
      <!--					<v-btn-->
      <!--						variant="outlined"-->
      <!--						block-->
      <!--						:disabled="false"-->
      <!--						color="primary"-->
      <!--						height="50"-->
      <!--						@click="emit('nextStep')"-->
      <!--					>-->
      <!--						Next-->
      <!--					</v-btn>-->
      <!--				</v-col>-->
      <!--			</v-col>-->
    </v-sheet>
  </v-container>

  <v-dialog
    v-model="login.dialog"
    title="Two-Factor Authentication"
    width="900"
  >
    <div class="bg-white pa-10">
      <v-alert
        :color="messageAlert.messageType"
        :model-value="messageAlert.showAlert"
        class="w-100 mb-3"
        closable
        @click:close="messageAlert.dismissedAlert"
      >
        <span v-html="messageAlert.message"></span>
      </v-alert>
      <TwoStepForm
        v-model="login.params"
        :loading="loadingTwoFactor"
        @submit="twoFactorSubmit"
      />
    </div>
  </v-dialog>

  <ValidationEmail @validated="emit('nextStep')" />
</template>

<script setup>
const TwoStepForm = Vue.defineAsyncComponent(() =>
  loadModule(`${SAS_URL}/src/components/guests/login/TwoStepForm.vue`, options)
);
const SignUp = Vue.defineAsyncComponent(() =>
  loadModule(`${SAS_URL}/src/components/guests/login/SignUp.vue`, options)
);
const ForgotPassword = Vue.defineAsyncComponent(() =>
  loadModule(
    `${SAS_URL}/src/components/guests/login/ForgotPassword.vue`,
    options
  )
);

const LoginSocialMedias = Vue.defineAsyncComponent(() =>
  loadModule(
    `${SAS_URL}/src/components/login/social-medias/Medias.vue`,
    options
  )
);

const ValidationEmail = Vue.defineAsyncComponent(() =>
  loadModule(
    `${SAS_URL}/src/components/guests/login/ValidationEmail.vue`,
    options
  )
);
const emit = defineEmits(["success", "nextStep"]);
const props = defineProps({
  redirect: {
    type: [Boolean],
    default: false,
  },
});
const userStore = window.useUserStore();
const validationEmailStore = window.useValidationEmail();
const password = Vue.ref({ view: false });
const loadingTwoFactor = Vue.ref(false);
const loadingSignUp = Vue.ref(false);
const loginOrSignUp = Vue.ref("login");
const errorSignUp = Vue.ref({ error: false, message: "" });
const messageAlert = Vue.ref({
  showAlert: false,
  message: "",
  messageType: "",
});
const defaultsInputs = {
  variant: "outlined",
  // hideDetails: true,
};

const defaults = {
  VTextField: defaultsInputs,
  VSelect: defaultsInputs,
  VAutocomplete: defaultsInputs,
  VCombobox: defaultsInputs,
  VFileInput: defaultsInputs,
  VTextarea: defaultsInputs,
};

const changeLoginOrSignUp = (value) => {
  loginOrSignUp.value = value;
};

const signUpUser = async (form) => {
  try {
    if (userStore.getLogin?.id && userStore.getUser?.seted_up === 0) {
      validationEmailStore.modalValidationEmail = true;
      return 
    }
    if (userStore.getLogin?.id) return emit("nextStep");

    loadingSignUp.value = true;

    const token = await window.$recaptcha("login");

    const formUpdated = {
      "g-recaptcha-response": token,
      guests: form,
    };

    const { data } = await userStore.setSignUpUser(formUpdated);
    if (data.message.includes("User already registered")) {
      errorSignUp.value = {
        error: true,
        message: data.message,
      };
    } else {
        errorSignUp.value = {
          error: false,
          message: '',
        };

      await userStore.setSyncUser();
      await userStore.twoFactorSetedUp();
      
      emit("nextStep");
    }
  } catch (e) {
    errorSignUp.value = {
      error: true,
      message: e.response.data.message,
    };
  } finally {
    loadingSignUp.value = false;
  }
};

const useVendorLogin = (options = {}) => {
  return Vue.ref({
    params: lodash.merge(
      {
        email: "",
        password: "",
      },
      options.params || {}
    ),
    loading: false,
    error: false,
    dialog: false,
    errors(field) {
      if (!this.error) return false;
      return this.error.message[field] || false;
    },
    async submit() {
      if (userStore.getLogin?.id && userStore.getUser?.seted_up === 0) {
        validationEmailStore.modalValidationEmail = true;
        return 
      }
      if (userStore.getLogin?.id) return emit("nextStep");
      if (this.loading) return;
      this.error = false;
      this.loading = true;
      try {
        const { data } = await userStore.setLoginUser(this.params);

        if (data.data.two_factor) {
          this.dialog = true;
          messageAlert.value.showAlert = true;
          messageAlert.value.message =
            "An email was sent with your MFA code. Please, enter the MFA code to complete sign-in.";
          messageAlert.value.messageType = "warning";
        }

        if (data.success) {
          window.env.saswp_vendor_id = data.data?.result?.account_id;
          window.env.saswp_vendor_token = data.data?.result?.access_token;
          this.response = data.data;

          errorSignUp.value = {
            error: false,
            message: '',
          };

          await userStore.setSyncUser();
          await userStore.twoFactorSetedUp();

          emit("nextStep");
        }
      } catch (e) {
        this.error = e.response ? e.response.data : e;
      }
      this.loading = false;
    },
  });
};

const login = useVendorLogin();

const twoFactorSubmit = async (form) => {
  loadingTwoFactor.value = true;
  await userStore
    .setTwoFactor(form)
    .then(async () => {
      login.value.dialog = false;

      await userStore.setSyncUser();
    })
    .catch((error) => {
      console.log("ERROR", error, error.response.data);
      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(() => {
      loadingTwoFactor.value = false;
    });
};
</script>
