<template>
  <user-block
    v-if="userMod"
    v-model="userMod"
    title="user_edit__title_card"
    btnText="user_edit__btn"
    @update="updateUser"
  />
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import userBlock from 'components/userBlock.vue'
  import { useUsersStore } from 'stores/users'
  import { parseIntString } from 'helpers/helpers'
  import type { User } from 'types/Users'

  const router = useRouter()
  const route = useRoute()
  const usersStore = useUsersStore()

  const userMod = ref<User | null>(null)
  const userId = computed(() => parseIntString(route.params.userId))

  if (usersStore.isInit) {
    userMod.value = userId.value 
      ? { ...usersStore.userById(userId.value) } as User
      : null
  }

  watch(() => usersStore.isInit, (isInit) => {
    if (isInit && userId.value && !userMod.value) {
      userMod.value = { ...usersStore.userById(userId.value) as User }
    }
  })

  async function updateUser () {
    if (userId.value && userMod.value) {
      await usersStore.update(userId.value, userMod.value)
      router.go(-1)
    }
  }

</script>
