<template>
  <project-block
    v-if="projectMod"
    v-model="projectMod"
    title="project_edit__title_card"
    btnText="project_edit__btn"
    @update="updateProject"
  />
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import projectBlock from 'components/projectBlock.vue'
  import { useProjectsStore } from 'stores/projects'
  import type { ProjectParams } from 'types/Project'

  const router = useRouter()
  const route = useRoute()
  const projectsStore = useProjectsStore()

  const projectId = computed(() => projectsStore.currentProjectId)
  const projectMod = ref<ProjectParams | null>(null)

  if (projectsStore.isInit) {
    projectMod.value = projectId.value 
      ? { ...projectsStore.projectById(projectId.value) } as ProjectParams 
      : null
  }

  watch(() => projectsStore.isInit, (isInit) => {
    if (isInit && projectId.value && !projectMod.value) {
      projectMod.value = { ...projectsStore.projectById(projectId.value) as ProjectParams }
    }
  })

  const updateProject = async () => {
    if (!projectId.value || !projectMod.value) return
    await projectsStore.update(projectId.value, projectMod.value)
    router.go(-1)
  }

</script>
