<template>
  <div>
    <div class="row items-center q-gutter-sm q-mb-sm q-mt-md">
      <div class="col-auto">
        <q-btn dense flat round icon="edit" @click="open">
          <q-tooltip class="bg-primary text-white">{{ t('children.editAddress') }}</q-tooltip>
        </q-btn>
      </div>
      <div class="col">
        <div class="text-caption">{{ label }}</div>
      </div>
    </div>
    <div class="q-pa-sm bg-grey-2 q-mb-sm">
      <div v-if="isEmpty" class="text-negative">{{ hintText }}</div>
      <div v-else>{{ formatted }}</div>
    </div>

    <AddressModal v-model="isOpen" :modelAddress="modalModel" :allowForeign="allowForeign" @save="onSave" @cancel="onCancel" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import AddressModal from './AddressModal.vue'
import type { Address as ModalAddress } from '../types/address'

// public Address shape required by the user
export interface AddressOut {
  street: string
  cap: string | number
  city: string
  country: { code: string; name: string }
  canton: string
}

const props = defineProps<{
  modelValue?: AddressOut | null
  label?: string
  allowForeign?: boolean
  hint?: string
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', v: AddressOut | null): void
  (e: 'save', v: AddressOut): void
  (e: 'cancel'): void
}>()

const { t } = useI18n()

const isOpen = ref(false)
const modalModel = ref<ModalAddress | null>(null)

const label = props.label || t('address')
const allowForeign = props.allowForeign ?? true

const formatted = computed(() => {
  const v = props.modelValue
  console.log('address input formatted', v)
  if (!v) return ''
  const countryName = v.country?.name || ''
  if (v.country.code === 'CH' ) {
    return [v.street, String(v.cap || ''), v.city, v.canton].filter(Boolean).join(', ')
  }
  return [v.street, String(v.cap || ''), v.city,  countryName].filter(Boolean).join(', ')
})

const isEmpty = computed(() => {
  const v = props.modelValue
  if (!v) return true
  // consider address empty when no meaningful fields are present
  return !(v.street || v.city || v.cap || (v.country && v.country.code))
})

const hintText = computed(() => props.hint || t('validation.insertAddress'))

function open() {
  const v = props.modelValue
  modalModel.value = v
    ? {
        street: v.street || '',
        zip: String(v.cap || ''),
        city: v.city || '',
        country: (v.country && v.country.code) || '',
        canton: v.canton || '',
        foreign: (v.country && v.country.code && v.country.code !== 'CH') ? true : false
      }
    : { street: '', zip: '', city: '', country: '', canton: '', foreign: true }
  isOpen.value = true
}

function onSave(a: ModalAddress) {
  // normalize country to object {code,name}
  let countryObj = { code: '', name: '' }
  if (!a.country) {
    countryObj = { code: '', name: '' }
  } else if (typeof a.country === 'string') {
    countryObj = { code: a.country, name: a.country }
  } else if (typeof a.country === 'object' && a.country !== null) {
    type CountryRef = { code?: string; name?: string }
    const c = a.country as CountryRef
    countryObj = { code: c.code || '', name: c.name || '' }
  }

  const out: AddressOut = {
    street: a.street || '',
    cap: a.zip || '',
    city: a.city || '',
    country: countryObj,
    canton: a.canton || ''
  }

  emit('update:modelValue', out)
  emit('save', out)
  isOpen.value = false
}

function onCancel() {
  emit('cancel')
  isOpen.value = false
}
</script>

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