<script lang='ts' setup>
import type { EmailVerifyClient, PhoneNumberVerifyClient } from "@/api/types";
import { closeOutline } from "ionicons/icons";
import { authClient } from "@/auth";
import EmailLogin from "./components/email.vue";
import PhoneNumberLogin from "./components/phone-number.vue";

const { t } = useI18n();
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

async function handleSignInEmail(value: EmailVerifyClient) {
  const { data } = await authClient.signIn.emailOtp({
    email: value.email,
    otp: value.otp,
  });
  if (data?.token) {
    userStore.setToken(data.token);
    userStore.updateProfile();
    useNavigateToRedirect(route.query.redirect as string);
  }
}
async function handleSignInPhoneNumber(value: PhoneNumberVerifyClient) {
  const { data } = await authClient.phoneNumber.verify({
    phoneNumber: value.phoneNumber,
    code: value.code,
    disableSession: false,
    updatePhoneNumber: false,
  });
  if (data?.token) {
    userStore.setToken(data.token);
    userStore.updateProfile();
    useNavigateToRedirect(route.query.redirect as string);
  }
}
function onClose() {
  useRouterBack();
}
</script>

<template>
  <IonPage>
    <IonHeader class="ion-no-border">
      <IonToolbar class="ion-toolbar">
        <ion-buttons slot="start">
          <ion-button @click="onClose">
            <ion-icon slot="icon-only" :icon="closeOutline" />
          </ion-button>
        </ion-buttons>
        <ion-button slot="end" fill="clear" @click="router.push('/auth/signup')">
          {{ t('auth.login.signupButton') }}
        </ion-button>
      </IonToolbar>
    </IonHeader>
    <IonContent :fullscreen="true" class="ion-padding">
      <div class="text-2xl font-semibold mb-5">
        {{ t('auth.login.title') }}
      </div>

      <ui-tabs class="mb-5">
        <ui-tab-pane name="username" :title="t('auth.login.username')">
          <div class="py-5">
            <EmailLogin @submit="handleSignInEmail" />
          </div>
        </ui-tab-pane>
        <ui-tab-pane name="phone" :title="t('auth.login.phone')">
          <div class="py-5">
            <PhoneNumberLogin @submit="handleSignInPhoneNumber" />
          </div>
        </ui-tab-pane>
      </ui-tabs>
    </IonContent>
  </IonPage>
</template>

<style scoped>
.title {
  margin-bottom: 30px;
}
</style>
