<template>
  <pn-page-card>
    <template #title>
      <div class="flex items-center justify-between col-grow">
        <div>
          {{$t('company_info__title_card')}}
        </div>
        <q-btn
          v-if="isFormValid && isDirty()"
          @click = "updateCompany()"
          flat round
          icon="mdi-check"
        />
      </div>
    </template>
    <pn-scroll-list>
      <company-info-block
        v-if="company"  
        v-model="company"
        @valid="isFormValid = $event"
      />
      <company-info-persons/>
    </pn-scroll-list>
  </pn-page-card>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import companyInfoBlock from 'src/components/companyInfoBlock.vue'
  import companyInfoPersons from 'src/components/companyInfoPersons.vue'
  import { useCompaniesStore } from 'stores/companies'
  import type { Company } from 'src/types'
  import { parseIntString, isObjEqual } from 'boot/helpers'

  const router = useRouter()
  const route = useRoute()
  const companiesStore = useCompaniesStore()

  const company = ref<Company>()
  const companyId = parseIntString(route.params.companyId)

  const isFormValid = ref(false)

  const originalCompany = ref<Company>({} as Company)

  const isDirty = () => {
    return company.value && !isObjEqual(originalCompany.value, company.value)
  }

  onMounted(async () => {
    if (companyId && companiesStore.companyById(companyId)) {
      const initial = companiesStore.companyById(companyId)
      
      company.value = { ...initial } as Company
      originalCompany.value = JSON.parse(JSON.stringify(company.value))
    } else {
      await abort()
    }
  })

  function updateCompany () {
    if (companyId && company.value) {
      companiesStore.updateCompany(companyId, company.value)
      router.back()
    }
  }

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

