<template>
  <q-card flat class="full-width q-pa-none">
    <q-card-section class="full-width">
      <div class="row items-center">
        <div class="col">
          <div class="text-h5">{{ t('INC') }}</div>
        </div>
        <div class="col-auto">
          <q-btn flat :label="t('button.prev')" @click="emitPrev" class="q-mr-sm" />
          <q-btn color="primary" :label="t('button.next')" @click="emitNext" />
        </div>
      </div>
      <q-separator class="q-my-sm" />

      <q-form class="q-gutter-md q-mt-md">
        <q-select
          v-model="form.employType"
          :options="employTypeOptions"
          :label="t('income.employTypeLabel')"
          :hint="!form.employType ? t('income.employTypeHint') : ''"
          :persistent-hint="!form.employType"
          emit-value
          map-options
        />

        <SimpleAttachment
          v-if="isFieldActive('salaryCertificate')"
          v-model="form.attachments.salaryCertificate"
          :label="t('income.attachments.salaryCertificate')"
          :session="'income'"
          :id="'salaryCertificate'"
          :autoload="false"
        />
        <SimpleAttachment
          v-if="isFieldActive('accountingDocuments')"
          v-model="form.attachments.accountingDocuments"
          :label="t('income.attachments.accountingDocuments')"
          :session="'income'"
          :id="'accountingDocuments'"
          :autoload="false"
        />
        <SimpleAttachment
          v-if="isFieldActive('avsCertificate')"
          v-model="form.attachments.avsCertificate"
          :label="t('income.attachments.avsCertificate')"
          :session="'income'"
          :id="'avsCertificate'"
          :autoload="false"
        />
        <SimpleAttachment
          v-if="isFieldActive('lppCertificate')"
          v-model="form.attachments.lppCertificate"
          :label="t('income.attachments.lppCertificate')"
          :session="'income'"
          :id="'lppCertificate'"
          :autoload="false"
        />
        <SimpleAttachment
          v-if="isFieldActive('unemploymentCertificate')"
          v-model="form.attachments.unemploymentCertificate"
          :label="t('income.attachments.unemploymentCertificate')"
          :session="'income'"
          :id="'unemploymentCertificate'"
          :autoload="false"
        />
      </q-form>
    </q-card-section>
  </q-card>
</template>

<script setup lang="ts">
import { computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { IncomeData, StepDescriptor } from '../../types/types'
import SimpleAttachment from '../SimpleAttachment.vue'
import { useUserstore } from '../../stores/userstore'
import { loadAttachmentsList } from '../../utils/api'
import { useIncomeStore } from '../../stores/income'

const props = defineProps<{ step?: StepDescriptor }>()
const emit = defineEmits(['next', 'prev'])

const { t } = useI18n()
const userStore = useUserstore()
const incomeStore = useIncomeStore()

const employTypeData = ["EMPLOYED", "SELF_EMPLOYED", "PENSIONER", "UNEMPLOYED"] as const

const incomeInfo = {
  EMPLOYED: {activeFields: ['salaryCertificate', 'accountingDocuments'], nextStep: 'marital'},
  SELF_EMPLOYED: {activeFields: [ 'accountingDocuments'], nextStep: 'marital'},
  PENSIONER: {activeFields: [ 'accountingDocuments', 'avsCertificate', 'lppCertificate'   ], nextStep: 'marital'},
  UNEMPLOYED: {activeFields: ['unemploymentCertificate'], nextStep: 'marital'}
} as const

const form = incomeStore.data as IncomeData

const attachmentKeys = [
  'salaryCertificate',
  'accountingDocuments',
  'avsCertificate',
  'lppCertificate',
  'unemploymentCertificate',
] as const

type AttachmentKey = keyof IncomeData['attachments']

const activeFieldSet = computed<Set<AttachmentKey>>(() => {
  const selected = form.employType
  if (!selected) return new Set<AttachmentKey>()

  const info = incomeInfo[selected as keyof typeof incomeInfo]
  const keys = (info?.activeFields ?? []) as unknown as AttachmentKey[]
  return new Set(keys)
})

function isFieldActive(key: AttachmentKey) {
  return activeFieldSet.value.has(key)
}

function clearInactiveAttachmentFields() {
  for (const key of attachmentKeys) {
    if (!isFieldActive(key)) {
      form.attachments[key].comments = ''
      form.attachments[key].attachments = []
    }
  }
}

watch(
  () => form.employType,
  () => {
    clearInactiveAttachmentFields()
  }
)

watch(
  () => form,
  () => {
    incomeStore.persist()
  },
  { deep: true }
)

const employTypeOptions = computed(() =>
  employTypeData.map(v => ({ label: t(`income.employType.${v}`), value: v }))
)

onMounted(async () => {
  const id = userStore.id
  if (!id) return

  // session folder name on backend
  const session = 'income'

  try {
    const list = await loadAttachmentsList({ id, session })
    for (const key of attachmentKeys) {
      const files = list[key]
      if (Array.isArray(files)) {
        form.attachments[key].attachments = [...files]
      }
    }
  } catch {
    // ignore network errors
  }
})

function emitNext() {
  emit('next', props.step?.next)
}

function emitPrev() {
  emit('prev', props.step?.prev)
}
</script>

<style scoped>
.q-card {
  width: 100%;
  margin: 0;
}
</style>
