<template>
  <div class="pp-user-form">
    <transition name="fadeIn" mode="out-in">
      <loader-ui v-if="loadingState === 'loading'" />

      <div v-else-if="loadingState === 'success'">
        <Title>{{ ppData.title }}</Title>

        <div>
          <Link
            :href="link"
            :external="true"
            :inline="false"
            class="btn pp-link"
          >
            {{ $_tr('seePP') }}
          </Link>
        </div>

        <BaseText class="infos" :html="true">
          {{ $_tr('introduction') }}
        </BaseText>

        <global-form
          form-id="pp-user-form"
          :endpoint="`content/p_and_p_regions/${ppRegionData.uuid}`"
          http-verb="put"
          :success-log="$_tr('logs.success')"
          :submit-button-text="$_tr('common.actions.save')"
          :reset-on-success="false"
          @onRequestSuccess="onSuccess"
        >
          <template #fields>
            <input-selectbox
              model-name="contact"
              form-id="pp-user-form"
              :label="$_tr('fields.contact')"
              :label-callback="user => $_username(user)"
              :async="{
                contentType: 'users',
                fields: ['uuid', 'lastname', 'firstname', 'image'],
                filters: {
                  'is_maintenance:eq': 0,
                  'status:eq': 1
                }
              }"
              :extra-options-callback="user => ({ image: user.image })"
              object-value-key="uuid"
              :rules="['required']"
              :default-value="
                getCheckedData(ppRegionData, ['contact', 'data', 0, 'uuid'])
              "
            >
              <template #default="{ node }">
                <user-item-selectbox
                  :username="getCheckedData(node, ['raw', 'label'])"
                  :image="
                    getCheckedData(node, ['raw', 'extraOptions', 'image'])
                  "
                />
              </template>
            </input-selectbox>

            <input-hidden
              model-name="uuid"
              form-id="pp-user-form"
              :default-value="ppRegionData.uuid"
            />

            <input-hidden
              model-name="type"
              form-id="pp-user-form"
              default-value="node"
            />

            <input-hidden
              model-name="bundle"
              form-id="pp-user-form"
              :default-value="ppRegionData.content_type"
            />
          </template>
        </global-form>
      </div>

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

<script>
import { Title, BaseText } from 'inside-collection/atoms'
import { Link } from 'inside-collection/components'

import { http } from '@inside-library/helpers/Http'
import { formatHref } from '@inside-library/helpers/Langs'

import UserItemSelectbox from '@inside-forms/displays/sub-components/fields-slots/UserItemSelectbox'

export default {
  name: 'PPUserForm',
  $_i18nRootPath: 'customs.pp.FORM',
  components: {
    UserItemSelectbox,
    Title,
    BaseText,
    Link
  },
  data() {
    return {
      loadingState: 'loading', // loading | success | failed
      ppRegionData: {},
      ppData: {}
    }
  },
  computed: {
    link() {
      return formatHref(
        {
          name: 'PPPage',
          params: {
            slug: this.ppData.slug[0]
          }
        },
        this.$_currentLang
      )
    }
  },
  async beforeMount() {
    try {
      const { data } = await http.get('content/p_and_p_regions', {
        filters: {
          uuid: this.$route.params.uuid
        },
        fields: [
          'uuid',
          'title',
          'content_type',
          {
            contact: {
              fields: ['uuid', 'lastname', 'firstname']
            }
          },
          {
            p_and_p: {
              fields: ['title', 'slug']
            }
          }
        ]
      })

      this.ppRegionData = data[0]
      this.ppData = this.ppRegionData.p_and_p
      this.loadingState = 'success'
    } catch (err) {
      this.loadingState = 'failed'
    }
  },
  methods: {
    onSuccess() {
      this.$router.push(this.link)
    }
  }
}
</script>

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

.pp-user-form {
  width: 90%;
  max-width: 800px;
  margin: var(--spacing-xl) auto 0;

  :deep(.loader-ui) {
    margin: auto;
  }

  h1 {
    text-align: center;

    @include fontSize(36);

    + div {
      display: flex;
      justify-content: center;
    }
  }

  .infos {
    margin: var(--spacing-l) 0;
    font-size: var(--font-size-labor);
  }

  .error {
    margin: calc(var(--spacing-m) * 10) 0 0;
    text-align: center;
  }

  .pp-link {
    display: inline-block;
    margin-top: var(--spacing-m);

    &.disabled {
      opacity: 0.4;
      pointer-events: none;
    }
  }
}
</style>
