<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("TAX") }}</div>
        </div>
        <div class="col-auto">
          <q-btn flat color="secondary" :label="t('button.prev')" @click="goPrev" class="q-mr-sm" />
          <q-btn color="primary" :label="t('button.next')" @click="goNext" />
        </div>
        </div>
        <q-separator class="q-my-sm" />

            <q-form ref="formRef" class="q-gutter-md q-mt-md">
              <div class="row items-center q-gutter-md q-mb-sm q-ml-none">
            <div class="col  q-ml-none">
              <q-toggle v-model="form.prevPreparedByUs" :label="t('taxpayer.prevPreparedByUs')" />
              </div>
            </div>
              <div v-if="form.prevPreparedByUs" class="q-mt-sm">
                <CommentAttachment v-model="form.prevDeclaration" :label="t('taxpayer.prevDeclaration')" :id="'taxpayer'"/>
              </div>

              <div>
                <q-input v-model="form.firstName" :label="t('taxpayer.firstName')" :rules="personalFirstNameRules" />
                <q-input v-model="form.lastName" :label="t('taxpayer.lastName')" :rules="personalLastNameRules" />
                <q-input v-model="form.birthDate" type="date" :label="t('taxpayer.birthDate')" :rules="personalBirthDateRules" />
                <AddressInput v-model="form.address" :label="t('taxpayer.address')" :allowForeign="true" @save="onAddressSave" @cancel="onAddressCancel" />
              </div>
            </q-form>
    </q-card-section>
  </q-card>
</template>




<script setup lang="ts">

import { onMounted, reactive, ref, nextTick, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useTaxstore } from '../../stores/taxstore'
import AddressInput from '../AddressInput.vue'
import type { StepDescriptor } from '../../types/types'
import CommentAttachment from '../CommentAttachment.vue'
import { type TaxpayerForm } from 'src/stores/taxpayer'

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

const step = props.step
const store = useTaxstore()
const form = reactive<TaxpayerForm>({} as TaxpayerForm)
const { t } = useI18n()

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

// address input binding (maps between form fields and AddressInput shape)
export type AddrOut = {
  street: string
  cap: string | number
  city: string
  country: { code: string; name: string }
  canton: string
}

// helper for validation messages
const requiredMessage = (fallback = 'Required') => {
  const msg = t('validation.required')
  return msg && msg !== 'validation.required' ? msg : fallback
}
const required = (msg?: string) => (v: unknown) => {
  const message = msg || requiredMessage()
  if (v === null || v === undefined) return message
  if (typeof v === 'string') return (v.trim() !== '') || message
  if (Array.isArray(v)) return v.length > 0 || message
  return true
}

const prevPrepared = computed(() => !!form.prevPreparedByUs)
const personalFirstNameRules = computed(() => (prevPrepared.value ? [] : [required()]))
const personalLastNameRules = computed(() => (prevPrepared.value ? [] : [required()]))
const personalBirthDateRules = computed(() => (prevPrepared.value ? [] : [required()]))
// address/zip/city use AddressModal for input; validation handled via modal

onMounted(async () => {
  // protect against undefined store data
  const saved = store.getTaxpayer() || {}
  Object.assign(form, saved)
  // load saved data from store into local form

  // ensure validation is not shown on mount
  await nextTick()
  formRef.value?.resetValidation?.()
})

async function goNext() {
  // validate, then persist into store and navigate
  try {
    const validateResult = await (formRef.value?.validate?.() ?? true)
    if (validateResult === false) return
  } catch {
    return
  }

  // persist into store then navigate
    store.setTaxpayer({
      prevPreparedByUs: form.prevPreparedByUs,
      prevDeclaration: form.prevDeclaration,
      firstName: form.firstName,
      lastName: form.lastName,
      birthDate: form.birthDate,
      address: form.address
    })

  emit('next', step.next)
}

function goPrev() {
  // save before navigating back
    store.setTaxpayer({
      prevPreparedByUs: form.prevPreparedByUs,
      prevDeclaration: form.prevDeclaration,
      firstName: form.firstName,
      lastName: form.lastName,
      birthDate: form.birthDate,
      address: form.address
    })
    emit('prev', step.prev)
  }



function onAddressCancel() {
  // no-op; AddressInput already preserves form via v-model
}

function onAddressSave() {
  // AddressInput already updated `form` through the computed `taxAddress`.
}
</script>

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