<template>
  <pn-page-template>
    <template #title>
      {{ $t(title) }}
    </template>
    <template #card-actions>
      <q-btn
        rounded color="primary"
        class="w100 fix-disabled-btn"
        :disable="!isFormValid"
        @click = "onSubmit"
        >
        {{ $t(btnText) }}
      </q-btn>
    </template>

    <div class="flex column items-center q-px-md q-pb-sm w100">
      <slot name="myCompany"/>
      <pn-image-selector
        v-model="companyMod.logo"  
        :size="100"
        :iconsize="80"
        class="q-pb-lg"
      />

      <q-form
        ref="formRef"
        @validation-success="isFormValid = true"
        @validation-error="isFormValid = false"
        class="q-gutter-y-lg w100"
        >
        <template 
          v-for="input in textInputs"
          :key="input.id"
          >
          <q-input
            v-model="companyMod[input.val]"
            no-error-icon
            dense
            filled
            :label="input.label ? $t(input.label) : void 0"
            :label-slot="Boolean(input.label)"
            class="w100 fix-bottom-padding"
            :class="input.val === 'name' ? '' : 'q-pt-sm'"
            :rules="input.rules"
            @update:model-value="formRef.validate()"
            :autogrow="input.val === 'description' || input.val === 'address'"
            debounce="300"
            >
            <template #prepend>
              <q-icon v-if="input.icon" :name="input.icon"/>
            </template>
            <template #label v-if="input.label">
              {{$t(input.label) }}
              <span v-if="input.val === 'name'" class="text-red">*</span>
            </template>
          </q-input>
        </template>
      </q-form>
    </div>
  </pn-page-template>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, } from 'vue'
  import pnImageSelector from 'components/pnImageSelector.vue'
  import { useInputRules } from 'composables/useInputRules'
  import { removeNullKeys, getFieldValue } from 'utils/helpers'
  import type { CompanyParams } from 'types/Company'

  const { inputRules } = useInputRules()

  const props = defineProps<{
    title: string,
    btnText: string,
    company?: CompanyParams
  }>()

  const emit = defineEmits(['update'])

  type CompType = {
    [K in keyof CompanyParams]: CompanyParams[K] extends number ? never : CompanyParams[K]
  }
  
  const companyMod = reactive<CompType>({
    name: props.company?.name ?? '',
    description: props.company?.description ?? '',
    site: props.company?.site ?? '',
    address: props.company?.address ?? '',
    phone: props.company?.phone ?? '',
    email: props.company?.email ?? '',
    logo: props.company?.logo ?? null
  })
  
  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_block__name', rules: [inputRules.require, inputRules.middleText] },
    { id:  2, val: 'description', label: 'company_block__description', rules: [inputRules.longText] },
    { id:  3, val: 'site', icon: 'mdi-web', rules: [inputRules.middleText] },
    { id:  4, val: 'address', icon: 'mdi-map-marker-outline', rules: [inputRules.longText] },
    { id:  5, val: 'phone', icon: 'mdi-phone-outline', rules: [inputRules.middleText] },
    { id:  6, val: 'email', icon: 'mdi-email-outline', rules: [inputRules.middleText] }
  ] as const

  const formRef = ref()
  const isFormValid = ref(false)

  function onSubmit() {
    const { logo, name, description, site, address, phone, email } = companyMod
    let logoValue: string | null | undefined = undefined

    if (typeof logo === 'string' && logo.startsWith('data:image')) logoValue = logo
    if (logo === null) logoValue = null

    const outData = {
      name: name.trim(),
      description: getFieldValue(description!.trim(), props.company?.description),
      site: getFieldValue(site!.trim(), props.company?.site),
      address: getFieldValue(address!.trim(), props.company?.address),
      phone: getFieldValue(phone!.trim(), props.company?.phone),
      email: getFieldValue(email!.trim(), props.company?.email),
      ...(logoValue !== undefined && { logo: logoValue })
    }

    emit('update', removeNullKeys(outData, ['logo']))
  }

  onMounted(async () => {
    await formRef.value.validate()
    if (!isFormValid.value) formRef.value.resetValidation()
  })

</script>

<style scoped>
  .q-field--with-bottom.fix-bottom-padding {
    padding-bottom: 0 !important
  }

  .input-fix :deep(.q-field__prepend.q-field__marginal) {
    height: auto !important;
  }
</style>
