<template>
  <form class="form" @submit.prevent="handleUpdate">
    <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="'email'"
          :placeholder="t('fields.email')"
          :rules="[isEmail]"
          v-model="email"
      />
      <ui-input
          :type="'text'"
          :placeholder="t('fields.phoneNumber')"
          :rules="[required]"
          v-model="phoneNumber"
      />
    </div>
    <div class="form__box">
      <ui-input
          :type="'password'"
          :placeholder="t('fields.newPassword')"
          :rules="[isPasswordValid]"
          v-model="password"
      />
      <ui-input
          :type="'password'"
          :placeholder="t('fields.confirmNewPassword')"
          :rules="[compareStrings]"
          v-model="confirmPassword"
      />
    </div>
    <ui-button
        class="form__button"
        :isLoading="loading"
    >
      {{ t('buttons.save') }}
    </ui-button>
  </form>
</template>

<script setup lang="ts">
import {useValidators} from "~/composables/rules";
import {useUserUpdating} from "~/composables/user/index.js";

const { t } = useI18n();
const userStore = useUserStore();

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

const user = computed(() => userStore.user);

const firstName = ref<string>('');
const lastName = ref<string>('');
const email = ref<string>('');
const phoneNumber = ref<string>('');
const password = ref<string>('');
const confirmPassword = ref<string>('');

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

const { updateUser, loading } = useUserUpdating();

watchEffect(() => {
  firstName.value = user.value?.firstName || '';
  lastName.value = user.value?.lastName || '';
  email.value = user.value?.email || '';
  phoneNumber.value = user.value?.phoneNumber || '';
});

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

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

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

  &__button {
    width: fit-content;
    padding-inline: 20px;
  }
}
</style>