<template>
  <form class="auth-form" @submit.prevent="onSubmit">
    <div class="auth-form__body">
      <AuthHeading title="کد تایید" step="otp" :phone-number="phoneNumber">
        <template #below>
          <button type="button" class="verify__resend" @click="onResend" :disabled="resending">
            {{ resending ? 'در حال ارسال...' : 'ارسال مجدد کد تایید' }}
          </button>
        </template>
      </AuthHeading>

      <TextField
        v-model="form.code"
        name="code"
        label="کد تایید را وارد کنید"
        inputmode="numeric"
        :convert-digits="true"
        :error="errors.code"
        @blur="validateAt('code', form.code)"
      >
        <template #appendIcon>
          <SvgIcon name="check" :size="22" color="var(--color-thd-gray)" />
        </template>
      </TextField>

      <BaseButton type="submit" text="تایید کد" :loading="submitting" custom-class="verify__submit">
        <template #appendIcon>
          <SvgIcon name="arrow-left" :size="22" color="#fff" />
        </template>
      </BaseButton>
    </div>

    <div class="verify__links">
      <div class="verify__link">
        <SvgIcon name="user" :size="12" color="#A7A7A7" />
        <button type="button" class="verify__link-btn" @click="emit('password-login')">
          ورود با رمز عبور
        </button>
      </div>
      <div class="verify__link">
        <SvgIcon name="phone" :size="12" color="#A7A7A7" />
        <button type="button" class="verify__link-btn" @click="emit('back')">
          تغییر شماره تلفن همراه
        </button>
      </div>
    </div>

    <div class="auth-form__footer">
      <AuthCopyright />
    </div>
  </form>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import useYup from '@/composables/useYup'
import useAuth from '@/composables/useAuth'
import BaseButton from '@/components/BaseButton.vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import TextField from '@/components/form/TextField.vue'
import { verifyCodeSchema } from '@/features/auth/schema'
import AuthHeading from '@/features/auth/components/AuthHeading.vue'
import AuthCopyright from '@/features/auth/components/AuthCopyright.vue'
import { usePasswordReset } from '@/features/auth/composables/usePasswordReset'
import { useRedirectAfterLogin } from '@/features/auth/composables/useRedirectAfterLogin'
import {
  useForgotPasswordMutation,
  useRequestLoginOtpMutation,
  useVerifyLoginOtpMutation,
  useResendVerificationCodeMutation,
  useVerifyCodeMutation,
  useVerifyForgotPasswordCodeMutation,
} from '@/services/query/auth'

const props = defineProps({
  phoneNumber: { type: String, default: '' },
  mode: { type: String, default: 'loginWithCode' },
})

const emit = defineEmits(['back', 'verified', 'password-login'])

const schema = verifyCodeSchema
const form = ref({ code: '' })
const { validate, validateAt, errors } = useYup(schema)

const { applySession } = useAuth()
const { setResetTicket } = usePasswordReset()
const router = useRouter()
const redirectAfterLogin = useRedirectAfterLogin()

const verifyLoginMutation = useVerifyLoginOtpMutation()
const verifySignupMutation = useVerifyCodeMutation()
const verifyForgotMutation = useVerifyForgotPasswordCodeMutation()
const resendCodeMutation = useResendVerificationCodeMutation()
const forgotMutation = useForgotPasswordMutation()
const requestLoginOtpMutation = useRequestLoginOtpMutation()

const submitting = computed(
  () =>
    verifyLoginMutation.isPending.value ||
    verifySignupMutation.isPending.value ||
    verifyForgotMutation.isPending.value
)

const resending = computed(
  () =>
    resendCodeMutation.isPending.value ||
    forgotMutation.isPending.value ||
    requestLoginOtpMutation.isPending.value
)

const onSubmit = async () => {
  const { isValid, payload } = await validate(form.value)
  if (!isValid) return
  const code = payload.code

  if (props.mode === 'loginWithCode') {
    const response = await verifyLoginMutation.mutateAsync({
      phone: props.phoneNumber,
      code,
      deviceName: 'web',
    })
    applySession(response?.data ?? response)
    redirectAfterLogin()
    return
  }

  if (props.mode === 'forgotPassword') {
    const response = await verifyForgotMutation.mutateAsync({ phone: props.phoneNumber, code })
    const data = response?.data ?? response
    setResetTicket({ phone: props.phoneNumber, token: data?.resetToken })
    router.push({ name: 'reset-password' })
    return
  }

  const response = await verifySignupMutation.mutateAsync({ phone: props.phoneNumber, code })
  applySession(response?.data ?? response)
  emit('verified', { phone: props.phoneNumber, code })
}

const onResend = async () => {
  if (!props.phoneNumber) return
  const body = { phone: props.phoneNumber }
  if (props.mode === 'forgotPassword') await forgotMutation.mutateAsync(body)
  else if (props.mode === 'loginWithCode') await requestLoginOtpMutation.mutateAsync(body)
  else await resendCodeMutation.mutateAsync(body)
}
</script>

<style lang="scss" scoped>
.auth-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex-grow: 1;

  &__body {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    padding: 1rem 0;

    @media (min-width: 768px) {
      flex-grow: 1;
      justify-content: center;
    }
  }

  &__footer {
    margin-top: auto;
    margin-bottom: 1rem;
    text-align: center;
    width: 100%;

    @media (min-width: 768px) {
      margin-top: 0;
    }
  }
}

.verify__resend {
  margin-top: 0.5rem;
  background: transparent;
  border: none;
  cursor: pointer;
  font-family: var(--font-family-fa);
  font-weight: 300;
  font-size: 0.75rem;
  color: #a7a7a7;
  text-decoration: underline;
  text-underline-offset: 4px;

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.verify__submit {
  margin-top: 1.5rem;
  width: 100%;
}

.verify__links {
  margin: 0.5rem 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.verify__link {
  display: inline-flex;
  align-items: start;
  gap: 0.25rem;
  font-family: var(--font-family-fa);
  font-size: 0.75rem;
  color: #a7a7a7;
}

.verify__link-btn {
  background: transparent;
  border: none;
  cursor: pointer;
  font-family: var(--font-family-fa);
  font-size: 0.75rem;
  color: #a7a7a7;
  padding: 0;

  &:hover {
    text-decoration: underline;
    color: var(--color-sec-gray);
  }
}
</style>
