<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-h6">{{ t('SID') }}</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="saveAndNext" />
        </div>
      </div>
      <q-separator class="q-my-sm" />

      <q-form ref="formRef" class="q-gutter-md q-mt-md">

        <q-toggle class="q-mb-md"          v-model="form.hasSideIncome"
          :label="t('sideIncome.hasSideIncome')"
        />


        <CommentAttachment
                class="q-mt-none"
                v-if="form.hasSideIncome"
                v-model="form.sideIncomeDocuments"
                :label="t('sideIncome.attachments')"
                :id="'documents'"
              />
      </q-form>
    </q-card-section>
  </q-card>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type { StepDescriptor } from '../../types/types'
import { useSideIncomeStore, type SideIncomeData } from '../../stores/sideIncome'

import CommentAttachment from '../CommentAttachment.vue'

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

const { t } = useI18n()
const store = useSideIncomeStore()
const form = store.data as SideIncomeData

const formRef = ref<{ validate?: () => Promise<boolean> | boolean; resetValidation?: () => void } | null>(null)

onMounted(async () => {
  await nextTick()
  formRef.value?.resetValidation?.()
})

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

async function saveAndNext() {
  try {
    const ok = await (formRef.value?.validate?.() ?? true)
    if (ok === false) return
  } catch {
    return
  }
  store.setSideIncome(form)
  emit('next', props.step?.next)
}

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

<style scoped>
.full-width { width: 100%; }
</style>
