<template>
  <form @submit.prevent="handleRegister()" class="form">
    <h2 class="form__title">{{ t('forms.register.title') }}</h2>
    <div class="form__box">
      <ui-input
          :type="'text'"
          :placeholder="t('fields.firstName')"
          :rules="[required]"
          v-model="firstName"
      />
      <ui-input
          :type="'text'"
          :placeholder="t('fields.lastName')"
          :rules="[required]"
          v-model="lastName"
      />
    </div>
    <div class="form__box">
      <ui-input
          :type="'text'"
          :placeholder="t('fields.phoneNumber')"
          :rules="[required]"
          v-model="phoneNumber"
      />
      <ui-input
          :type="'email'"
          :placeholder="t('fields.email')"
          :rules="[isEmail]"
          v-model="email"
      />
    </div>
    <ui-input
        :type="'password'"
        :placeholder="t('fields.password')"
        :rules="[isPasswordValid]"
        v-model="password"
    />
    <ui-input
        :type="'password'"
        :placeholder="t('fields.confirmPassword')"
        :rules="[compareStrings]"
        v-model="confirmPassword"
    />
    <ui-button
        class="form__button"
        :isDisabled="!isFormValid"
        :isLoading="loading"
    >
      {{ t('buttons.register') }}
    </ui-button>
    <p class="form__login">
      {{ t('forms.register.login') }}
      <ui-link
          @click="appStore.setActiveState('login')"
      >
        {{ t('forms.login.title') }}
      </ui-link>
    </p>
  </form>
</template>

<script setup>
import {useValidators} from "~/composables/rules";
import {useRegister} from "~/composables/auth/index.js";

const { t } = useI18n()
const appStore = useAppStore()

const { required, isEmail, isPasswordValid } = useValidators()

const firstName = ref('')
const lastName = ref('')
const phoneNumber = ref('')
const email = ref('')
const password = ref('')
const confirmPassword = ref('')

const compareStrings = (v) => {
  if (v === password.value) return true
  return t('errors.compare')
}

const isFormValid = computed(() => {
  return (
    required(firstName.value) === true &&
    required(lastName.value) === true &&
    required(phoneNumber.value) === true &&
    isEmail(email.value) === true &&
    isPasswordValid(password.value) === true &&
    compareStrings(confirmPassword.value) === true
  )
})

const { register, loading } = useRegister();

async function handleRegister() {
  await register(
      firstName.value,
      lastName.value,
      phoneNumber.value,
      email.value,
      password.value,
      confirmPassword.value
  );
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-direction: column;
  gap: 20px;

  &__title {
    font-size: 36px;
    color: $accent;
  }

  &__box {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  &__login {
    display: flex;
    align-items: center;
    gap: 5px;

    font-size: 12px;
  }
}
</style>