<template>
  <div class="flex column items-center col-grow q-px-lg q-pt-sm">
    <pn-image-selector :size="100" :iconsize="80" class="q-pb-xs" v-model="modelValue.logo"/>
    
    <q-input
      v-for="input in textInputs"
      :key="input.id"
      v-model.trim="modelValue[input.val]"
      dense
      filled
      class = "q-mt-md w100"
      :label = "input.label ? $t(input.label) : void 0"
      :rules="input.val === 'name' ? [rules[input.val]] : []"
      >
      <template #prepend>
        <q-icon v-if="input.icon" :name="input.icon"/>
      </template>
    </q-input>

  </div>
</template>

<script setup lang="ts">
  import { watch, computed } from 'vue'
  import type { CompanyParams } from 'src/types'
  import { useI18n } from 'vue-i18n'
  const { t }= useI18n()

  const modelValue = defineModel<CompanyParams>({
    required: false,
    default: () => ({
      name: '',
      logo: '',
      description: '',
      site: '',
      address: '',
      phone: '',
      email: ''
    })
  })

  const emit = defineEmits(['valid'])
  const rulesErrorMessage = {
    name: t('company_card__error_name')
  }

  const rules = {
    name: (val :CompanyParams['name']) => !!val?.trim() || rulesErrorMessage['name']
  }

  const isValid = computed(() => {
    const checkName = rules.name(modelValue.value.name)
    return { name: checkName && (checkName !== rulesErrorMessage['name']) }
  })

  watch(isValid, (newVal) => {
    const allValid = Object.values(newVal).every(v => v)
    emit('valid', allValid)
  }, { immediate: true})

  interface TextInput {
    id: number
    label?: string
    icon?: string
    val: keyof CompanyParams
    rules: ((value: string) => boolean | string)[]
  }
  const textInputs: TextInput[] = [
    { id:  1, val: 'name', label: 'company_info__name', rules: [] },
    { id:  2, val: 'description', label: 'company_info__description', rules: [] },
    { id:  3, val: 'site', icon: 'mdi-web', rules: [] },
    { id:  4, val: 'address', icon: 'mdi-map-marker-outline', rules: [] },
    { id:  5, val: 'phone', icon: 'mdi-phone-outline', rules: [] },
    { id:  6, val: 'email', icon: 'mdi-email-outline', rules: [] },
  ]
  
</script>

<style>
</style>
