<template>
  <pn-page-card>
    <template #title>
      <div class="flex items-center justify-between col-grow">
        <div>
          <span>{{ $t('project_card__project_card') }}</span>
        </div>
        <q-btn
          v-if="isFormValid && isDirty()"
          @click="updateProject()"
          flat
          round
          icon="mdi-check"
        />
      </div>
    </template>

    <pn-scroll-list>
      <project-info-block
        v-if="project"
        v-model="project"
        @valid="isFormValid = $event"  
      />
    </pn-scroll-list>
  </pn-page-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useProjectsStore } from 'stores/projects'
import projectInfoBlock from 'src/components/projectInfoBlock.vue'
import type { Project } from '../types'
import { parseIntString, isObjEqual } from 'boot/helpers'

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

const project = ref<Project>()
const id = parseIntString(route.params.id)

const isFormValid = ref(false)

const originalProject = ref<Project>({} as Project)

const isDirty = () => {
  return true // project.value && !isObjEqual(originalProject.value, project.value)
}

onMounted(async () => {
  if (id && projectsStore.projectById(id)) {
    const initial = projectsStore.projectById(id)
    
    project.value = { ...initial } as Project
    originalProject.value = JSON.parse(JSON.stringify(project.value))
  } else {
    await abort()
  }
})

function updateProject () {
  if (id && project.value) {
    projectsStore.updateProject(id, project.value)
    router.back()
  }
}

async function abort () {
  await router.replace({name: 'projects'})
}
</script>

<style>
</style>
