<template>
  <div class="brand-form-generator">
    <global-form
      ref="form"
      :steps="[]"
      :form-id="formID"
      @onDataChange="setTemplateData"
      @onErrorChange="setTemplateError"
    >
      <template #fields>
        <component
          :is="`input-${field.type}`"
          v-for="field in fieldsArray"
          ref="fields"
          :key="field.name"
          :form-id="formID"
          :modelName="field.name"
          :rules="field.rules"
          :defaultValue="field.defaultValue"
          :label="field.label && field.label[$_currentLang]"
          :inputData="field.options && field.options[$_currentLang]"
        />
      </template>

      <template #submitForm>
        <transition name="fadeIn" mode="out-in">
          <div v-if="generateState === 'idle'" class="brand-form-submit">
            <div class="df-center-y">
              <Button @click.stop.prevent="redirectToPreview">
                {{ $_tr('preview') }}
              </Button>

              <Button
                :disabled="Object.keys(tplError).length !== 0"
                class="ml-m"
                @click="onGenerate"
              >
                {{ $_tr('generate') }}
              </Button>
            </div>
          </div>

          <loader-ui v-else-if="generateState === 'inprogress'" />

          <p
            v-else-if="generateState === 'success'"
            class="brand-form-generator__success"
          >
            {{ $_tr('success') }}
          </p>

          <p v-else class="brand-form-generator__error">
            {{ $_tr('error') }}
          </p>
        </transition>
      </template>
    </global-form>
  </div>
</template>

<script>
import { Button } from 'inside-collection/components'

import SignatureGenerator from './mixins/signature-generator'
import CardGenerator from './mixins/card-generator'

export default {
  name: 'brand-forms-generator',
  $_i18nRootPath: 'customs.BRAND_FORMS_GENERATOR',
  components: {
    Button
  },
  mixins: [SignatureGenerator, CardGenerator],
  $_generateSteps: ['idle', 'inprogress', 'success', 'error'],
  props: {
    formID: {
      type: String,
      required: true
    },
    fieldsArray: {
      type: Array,
      required: true
    },
    filename: {
      type: String,
      default: 'image'
    },
    templateType: {
      type: String,
      default: 'card'
    },
    width: {
      type: Number
    },
    height: {
      type: Number
    }
  },
  data() {
    return {
      tplData: {},
      tplError: {},
      brandName: this.formID.replace(`_${this.templateType}`, ''),
      extension: this.templateType === 'card' ? 'pdf' : 'jpg',
      generateState: 'idle'
    }
  },
  computed: {
    getURLsInfos() {
      return this.$store.getters.getURLsInfos
    }
  },
  beforeUnmount() {
    this.setStoreAction('setCurrentTemplateData', {})
  },
  methods: {
    /**
     * Get data from global-forms and store them
     */
    setTemplateData(tplData) {
      this.$store.commit('setCurrentTemplateData', tplData)
      this.tplData = tplData
    },
    setTemplateError(tplError) {
      this.$store.commit('setCurrentTemplateError', tplError)
      this.tplError = tplError
    },
    /**
     * Manually reset of the form
     */
    resetForm() {
      this.setStoreAction('deleteForm', {
        id: this.formID
      })

      this.$refs.form.resetForm()
    },
    redirectToPreview() {
      const targetElement = document.querySelector('#brand-forms__preview')

      if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth' })
      }
    },
    onGenerate() {
      const action = () =>
        new Promise((resolve, reject) => {
          if (this.templateType === 'signature') {
            this.generateSignature()
          } else {
            this.generateCard()
          }

          resolve()
        })

      const content = {
        item: {
          body: this.$_tr('modal.text'),
          actionTitle: this.$_tr('modal.button')
        },
        content: 'action'
      }

      this.triggerModal('action', 'static', content, {
        layout: 'center',
        action,
        transition: 'fadeIn'
      })
    }
  }
}
</script>

<style scoped lang="scss">
@use '@inside-library/styles/mixins/partials/common-mixin' as *;

.brand-form-generator {
  :deep(.global-form__submit) {
    display: flex;
    justify-content: flex-end;
    margin-top: 35px;

    a {
      margin-right: 15px;
    }
  }

  :deep(.loader-ui) {
    width: 30px;
    height: 30px;
    padding-top: 0;
  }

  &__success {
    color: var(--color-valid);

    @include fontSize(18);
  }
}

.brand-form-submit {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;

  > div {
    justify-content: flex-end;
  }
}
</style>
