<template>
  <div class="add-form-modal">
    <div class="header">
      <div class="cross-close" @click="closeBanner" />
    </div>

    <div class="body">
      <h1>
        {{ heritedData.multiUpload ? $_tr('multipleTitle') : $_tr('title') }}
      </h1>

      <global-form :formId="formId" :use-submit-slot="false">
        <template #fields>
          <input-text
            v-if="!heritedData.multiUpload"
            model-name="title"
            :label="$_tr('titleLabel')"
            :default-value="$_tr('titleFile')"
            @onDataChange="onTitleChange"
          />

          <input-dropzone
            :model-name="heritedData.contents"
            :options="{
              uploadMultiple: false,
              chunking: false,
              maxFiles: heritedData.multiUpload ? 10 : 1
            }"
            @fileLoaded="onFileAdded"
            @onFileRemoved="onFileRemoved"
            @onDataChange="onDataChange"
          />

          <section v-for="section in sections" :key="section.name">
            <p class="title">{{ section.title }}</p>

            <component
              v-for="field in sectionField(section.name)"
              :is="`input-${field.type}`"
              :key="field.name"
              v-bind="field"
            >
              <template v-if="field.useUserTemplate" #default="{ node }">
                <user-item-selectbox
                  :username="getCheckedData(node, ['raw', 'label'])"
                  :image="
                    getCheckedData(node, ['raw', 'extraOptions', 'image'])
                  "
                />
              </template>
            </component>
          </section>
        </template>
      </global-form>

      <div class="submit">
        <div>
          <transition name="fadeIn">
            <div v-if="uploading && hasParentFolder" class="uploading">
              <Loader size="m" boxSize="xs" />

              <p>
                {{
                  $_tr('uploading', [uploadCounter, Object.keys(files).length])
                }}
              </p>
            </div>
          </transition>
        </div>

        <div class="actions">
          <button class="cancel btn-reset">
            {{ $_tr('common.actions.cancel') }}
          </button>

          <button class="post btn" @click="onSubmit">
            {{ $_tr('common.actions.publish') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import UserItemSelectbox from '@inside-forms/displays/sub-components/fields-slots/UserItemSelectbox'
import GlobalFormMixin from '@inside-forms/mixins/global-form-mixin'
import { http } from '@inside-library/helpers/Http'
import { Loader } from 'inside-collection/atoms'

export default {
  name: 'add-form-modal',
  $_i18nRootPath: 'customs.GED.modal',
  components: {
    UserItemSelectbox,
    Loader
  },
  mixins: [GlobalFormMixin],
  data() {
    return {
      formId: 'add-form-modal',
      files: {},
      currentFolder: null,
      uploading: false,
      site: null,
      client: null,
      uploadCounter: 0,
      title: null,
      hasParentFolder: false
    }
  },
  computed: {
    langs() {
      return process.env.GLOBAL.availableLangs.map(lang => ({
        label: this.$_tr(`fields.langcode.values.${lang}`),
        value: lang
      }))
    },
    sections() {
      return [
        {
          name: 'advanced',
          title: this.$_tr('section.advanced')
        }
      ]
    },
    sectionField() {
      return name => this.fields.filter(field => field.sectionName === name)
    },
    fields() {
      return [
        {
          modelName: this.heritedData.parents,
          sectionName: 'advanced',
          type: 'selectbox',
          label: this.$_tr('fields'),
          'default-value': [this.currentFolderUuid],
          async: {
            contentType: this.heritedData.parents,
            fields: ['uuid', 'title']
          },
          'object-label-key': 'title',
          'object-value-key': 'uuid',
          clearable: false,
          callback: data => {
            this.currentFolder = data

            return data
          }
        },
        {
          modelName: 'clients',
          sectionName: 'advanced',
          type: 'hidden',
          label: 'Client',
          readonly: true,
          defaultValue: this.client.title,
          callback: () => this.client.uuid
        },
        {
          modelName: 'sites',
          sectionName: 'advanced',
          type: 'hidden',
          label: 'Site',
          readonly: true,
          defaultValue: this.site.title,
          callback: () => this.site.uuid
        }
      ]
    },
    currentFolderUuid() {
      return this.$store.getters.getCurrentFolderUuid
    }
  },
  watch: {
    uploadCounter(value) {
      if (value === Object.keys(this.files).length && this.hasParentFolder) {
        this.$_triggerToast({
          type: 'success',
          text: this.$_tr('toast.success'),
          duration: 2000
        })

        if (
          this.currentFolderUuid === this.currentFolder[0] &&
          this.hasParentFolder
        ) {
          this.setStoreAction(
            'fetchFolderData',
            { uuid: this.currentFolderUuid },
            true
          )
        }

        this.closeModal('add-form-0')
        window.location.reload()
      }
    }
  },
  beforeMount() {
    this.client = this.$store.getters.getUserInformation('client')
    this.site = this.$store.getters.getUserInformation('site')
  },
  methods: {
    onDataChange(data) {
      if (data.value) {
        const file = Object.entries(this.files).find(item =>
          data.value.includes(item[1].filename)
        )

        if (file) {
          this.files[file[0]].value = data.value
        }
      }
    },
    onTitleChange(data) {
      this.title = data.value
    },
    onFileAdded(file) {
      this.files[file.upload.uuid] = {
        filename: file.upload.filename
      }
    },
    onFileRemoved(file) {
      if (this.uploadCounter === 0) {
        delete this.files[file.upload.uuid]
      }
    },
    onSubmit() {
      this.uploading = true
      const form = this.$store.getters.getForm(this.formId)
      const fields = form.fields || {}

      const folderType = form.fields.space_folders
        ? form.fields.space_folders.id
        : form.fields.shared_folders.id

      if (form.fields[folderType].value[0]) {
        this.hasParentFolder = true

        Object.entries(this.files).forEach(async file => {
          const params = {
            title: this.title || file[1].filename,
            file: file[1].value,
            [this.heritedData.parents]:
              fields[this.heritedData.parents].formattedValue,
            type: 'node',
            bundle: this.heritedData.contents,
            fields: ['uuid', 'title'],
            langcode: this.$_currentLang,
            sites: this.site.uuid,
            clients: this.client.uuid
          }

          try {
            await http.post(`content/${this.heritedData.contents}`, params)
            this.uploadCounter++
          } catch (err) {
            new Error(err)
          }
        })
      } else {
        this.$_triggerErrorToast({
          text: this.$_tr('toast.folderError')
        })
      }
    },
    closeBanner() {
      this.closeModal('add-form-0')
    }
  }
}
</script>

<style lang="scss" scoped>
.add-form-modal {
  .header {
    position: relative;
    background-color: var(--color-admin);
    height: 70px;

    .cross-close {
      position: absolute;
      top: var(--spacing-l);
      right: var(--spacing-l);

      &::before,
      &::after {
        background: var(--color-light);
      }
    }
  }

  .body {
    margin: var(--spacing-3xl);

    h1 {
      text-align: center;
    }

    #add-form-modal {
      margin-top: var(--spacing-3xl);
    }

    section {
      padding: var(--spacing-xxl);
      margin-top: var(--spacing-xxl);
      box-shadow: var(--shadow-default);

      .title {
        margin-bottom: var(--spacing-l);
        font-size: var(--font-size-h4);
      }
    }

    .submit {
      display: flex;
      justify-content: space-between;
      margin-top: var(--spacing-xxl);
    }

    .uploading {
      display: flex;
      align-items: center;
      width: 32px;

      .ds-loader-container {
        margin-right: var(--spacing-xs);
      }
    }

    .actions {
      display: flex;
      align-items: center;

      > * {
        margin-right: var(--spacing-l);

        &:last-child {
          margin: 0;
        }
      }

      .post,
      .cancel {
        font-size: var(--font-size-h5);
      }

      .post {
        padding: var(--spacing-s) var(--spacing-m);
        border-radius: var(--spacing-l);
        background: var(--color-admin);
        border: 1px solid var(--color-admin);

        &:hover {
          color: var(--color-admin);
          background: var(--color-light);
        }
      }

      .cancel {
        color: var(--color-grey);

        @include transition(color 0.4s);

        &:hover {
          color: var(--color-invalid);
        }
      }
    }

    ::v-deep {
      .vue-dropzone.dropzone {
        position: relative;
        display: grid;
        grid-template-columns: 1fr 1fr 1fr 1fr;
        grid-gap: var(--spacing-l);

        .dz-preview {
          width: auto;
        }
        .dz-message {
          position: absolute;
          top: 50%;
          left: 50%;
          margin: 0;
          transform: translate(-50%, -50%);
        }

        .dz-remove {
          color: var(--color-light);

          &:hover {
            color: var(--color-light);
          }
        }
      }

      .input-selectbox .input-choices.input--placeholder > label,
      .input-selectbox .input-choices.input--focused > label,
      .input-selectbox .input-choices.input--filled > label {
        color: var(--color-admin);
      }
    }
  }
}
</style>
