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

    <pn-scroll-list>
      <div class="flex column items-center q-pa-md q-pb-sm">
        <pn-image-selector
          v-model="projectMod.logo"
          :size="100" 
          :iconsize="80"
          type="rounded"
          class="q-pb-lg" 
        />
        <div class="q-gutter-y-lg w100">
          <q-input
            v-model="projectMod.name"
            no-error-icon
            dense
            filled
            label-slot
            class = "w100 fix-bottom-padding"
            :rules="[rules.name]"
            >
            <template #label>
              {{ $t('project_block__project_name') }} <span class="text-red">*</span>
            </template>
          </q-input>
          
          <q-input
            v-model="projectMod.description"
            dense
            filled
            autogrow
            class="w100 q-pt-sm"
            :label="$t('project_block__project_description')"
          />
        </div>
      </div>
    </pn-scroll-list>
  </pn-page-card>

</template>

<script setup lang="ts">
  import { computed, reactive } from 'vue'
  import { useI18n } from 'vue-i18n'
  import type { ProjectParams } from 'types/Project'
  import { removeNullKeys } from 'utils/helpers'

  const { t } = useI18n()

  const props = defineProps<{
    title: string,
    btnText: string,
    project?: ProjectParams
  }>()
  
  const emit = defineEmits(['update'])

  const projectMod = reactive({
    name: props.project?.name ?? '',
    description: props.project?.description ?? '',
    logo: props.project?.logo ?? null
  })

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

  const isFormValid = computed(() => {
    const validations = {
      name: projectMod.name && rules.name(projectMod.name) === true
    }
    
    return Object.values(validations).every(Boolean)
  })

  function onSubmit() {
    const outData = {
      name: projectMod.name,
      description: projectMod.description ?? (typeof props.project?.description === 'string' ? '' : null),
      logo: projectMod.logo
    }
    emit('update', removeNullKeys(outData))
  }

</script>

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