<template>
  <company-block
    v-if="companyMod"
    v-model="companyMod"
    title="company_edit__title_card"
    btnText="company_edit__btn"
    @update="updateCompany"
  >
  <template #myCompany v-if="companyMod.is_own">
    <div class="q-mb-md flex w100 justify-center">
      <div class="flex items-center text-amber-10">
        <q-icon name="star" class="q-pr-xs"/>
        {{ $t('company_edit__my_company') }}
      </div>
      <div class="text-caption" align="center" style="white-space: pre-wrap;">
        {{ $t('company_edit__my_company_hint') }}
      </div>
    </div>
  </template>
  </company-block>
</template>

<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import companyBlock from 'components/companyBlock.vue'
  import { useCompaniesStore } from 'stores/companies'
  import { parseIntString } from 'helpers/helpers'
  import type { CompanyParams } from 'types/Company'

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

  const companyMod = ref<CompanyParams | null>(null)
  const companyId = computed(() => parseIntString(route.params.companyId))

  if (companiesStore.isInit) {
    companyMod.value = companyId.value 
      ? { ...companiesStore.companyById(companyId.value) } as CompanyParams 
      : null
  }

  watch(() => companiesStore.isInit, (isInit) => {
    if (isInit && companyId.value && !companyMod.value) {
      companyMod.value = { ...companiesStore.companyById(companyId.value) as CompanyParams }
    }
  })

  async function updateCompany () {
    if (companyId.value && companyMod.value) {
      await companiesStore.update(companyId.value, companyMod.value)
      router.go(-1)
    }
  }

</script>

