<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("MAR") }}</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="form q-gutter-md q-mt-md">
        <!-- explicit fields for marital step (no v-for) -->
          <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.alimentiVersati" :label="t('children.alimentiVersati')" />
            </div>
          </div>
          <div v-if="form.alimentiVersati" class="row">
            <CommentAttachment v-model="form.alimentiCommenti" :label="t('informazionesualimenti')" :id="'marital'"/>
          </div>
        <!-- maritalStatus (enum) -->
        <q-select
          :model-value="form.maritalStatus"
          :label="$t('marital.maritalStatus')"
          @update:model-value="val => form.maritalStatus = val"
          :options="getOptions()"
          :rules="maritalStatusRules"
          emit-value
          map-options
        />

        <!-- spouse fields (visible only when married/partnered) -->
        <template v-if="maritalconfig[form.maritalStatus]?.showSpouseData">
          <div class="row ">{{ $t(maritalconfig[form.maritalStatus]?.data) }}</div>
          <q-input
            :model-value="form.spouseFirstName"
            @update:model-value="val => form.spouseFirstName = val"
            :label="$t('marital.spouse.firstName')"
            :rules="[required()]"
          />

          <q-input
            :model-value="form.spouseLastName"
            @update:model-value="val => form.spouseLastName = val"
            :label="$t('marital.spouse.lastName')"
            :rules="[required()]"
          />

          <q-input
            :model-value="form.spouseBirthDate"
            @update:model-value="val => form.spouseBirthDate = val"
            :label="$t('marital.spouse.birthDate')"
            type="date"
            :rules="[required()]"
          />

          <q-input
            v-if="maritalconfig[form.maritalStatus]?.deadDate"
            :model-value="form.spouseDeadDate"
            @update:model-value="val => form.spouseDeadDate = val"
            :label="$t(maritalconfig[form.maritalStatus]?.deadDateLabel)"
            type="date"
            :rules="[required()]"
          />

          <AddressInput
            v-if="maritalconfig[form.maritalStatus]?.address"
            v-model="form.spouseAddress"
            :hint="t(maritalconfig[form.maritalStatus]?.addressHint)"
            :label="t('taxpayer.address')"
            :allowForeign="true"
            @save="onSpouseAddressSave"
            @cancel="onSpouseAddressCancel"
          />

        </template>

      </q-form>
    </q-card-section>


  </q-card>
</template>

<script setup lang="ts">
import { reactive, onMounted, nextTick, ref, } from 'vue'
import type { StepDescriptor } from '../../types/types'
import { useI18n } from 'vue-i18n'
import { useTaxstore } from '../../stores/taxstore'
import type { AddressOut } from '../AddressInput.vue'
import AddressInput from '../AddressInput.vue'
import CommentAttachment from '../CommentAttachment.vue'
import {type  MaritalData } from 'src/stores/marital'

interface option{ label: string; value: string }

type Options = option[]

const maritalItems = [
  'celibate',
  'maried',
  'registrated',
  'widower',
  'deadunion',
  'divorced',
  'unionlegal',
  'separated',
  'uniondisappeared',
]

const maritalconfig = {
  celibate:{
    showSpouseData: false,
    address: ''
    ,data: ''
    ,deadDate: false
    ,deadDateLabel: ''
    ,addressHint: ''
  },
  maried:{
    showSpouseData: true,
    address: 'indirizzocogniuge'
    ,data: 'daticogniuge'
    ,deadDate: false
    ,deadDateLabel: ''
    ,addressHint: 'inserireindirizzocogniuge'
  },
  registrated:{
    showSpouseData: true,
    address: 'indirizzopartner'
    ,data: 'datipartner'
    ,deadDate: false
    ,deadDateLabel: ''
    ,addressHint: 'inserireindirizzopartner'
  },
  widower:{
    showSpouseData: true,
    address: ''
    ,data: 'daticogniugedefunto'
    ,deadDate: true
    ,deadDateLabel: 'datadecesso'
    ,addressHint: ''
  },
  deadunion:{
    showSpouseData: true,
    address: ''
    ,data: 'datideadpartner'
    ,deadDate: true
    ,deadDateLabel: 'datadecesso'
    ,addressHint: ''
  },
  divorced:{
    showSpouseData: true,
    address: 'indirizzoexcogniuge'
    ,data: 'datiexcogniuge'
    ,deadDate: false
    ,deadDateLabel: ''
    ,addressHint: 'inserireindirizzocogniuge'
  },
  unionlegal:{
    showSpouseData: true,
    address: 'indirizzoexpartner'
    ,data: 'datideadexpartner'
    ,deadDate: true
    ,deadDateLabel: 'datascioglimento'
    ,addressHint: 'inserireindirizzopartner'
  },
  separated:{
    showSpouseData: true,
    address: 'indirizzoexcogniuge'
    ,data: 'datiexcogniuge'
    ,deadDate: false
    ,deadDateLabel: ''
    ,addressHint: 'inserireindirizzocogniuge'
  },
  uniondisappeared:{
    showSpouseData: true,
    address: ''
    ,data: 'datidisapparizedpartner'
    ,deadDate: true
    ,deadDateLabel: 'datascomparsa'
    ,addressHint: ''
  }
}

const { t } = useI18n()
const store = useTaxstore()
const { step } = defineProps<{ step?: StepDescriptor }>()
const emit = defineEmits(['next', 'prev'])
// reactive form accepts dynamic keys produced from schema
const form = reactive<MaritalData>({} as MaritalData)

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

// spouse address modal state
const isSpouseAddressDialogOpen = ref(false)

function getOptions() {
  const items = [] as Options
  for (const item of maritalItems){
    items.push({label:t(`maritalItem.${item}`), value:item})
  }
  return items
}

function onSpouseAddressCancel() {
  isSpouseAddressDialogOpen.value = false
}

function onSpouseAddressSave(a: AddressOut) {
  form.spouseAddress = a
  isSpouseAddressDialogOpen.value = false
}

// 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
  return true
}

const maritalStatusRules = [required()]

onMounted(async () => {
  const saved = store.getMarital()
  // initialize form with saved marital data (map keys directly)
  if (saved) {
    Object.assign(form, saved)
  }
  // clear any validation state on mount so fields are not marked invalid initially
  await nextTick()
  formRef.value?.resetValidation?.()
})

function buildPayload(): MaritalData {
  const payload = {} as MaritalData
  // copy all form fields into payload
  for (const [k, v] of Object.entries(form)) {
    payload[k] = v
  }
  return payload
}

async function saveAndNext() {
  const ok = await formRef.value?.validate?.()
  if (ok === false) return
  const payload = buildPayload()
  store.setMarital(payload)
  emit('next', step?.next)
}

function emitPrev() {
  const payload = buildPayload()
  store.setMarital(payload)
  emit('prev', step?.prev)
}

// expose buildPayload so parent stepper can trigger save/navigation if needed
defineExpose({ buildPayload })
</script>

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