<template>
  <global-form
    :format-data="formatData"
    :endpoint="endpoint"
    form-id="restaurants-modal-form"
    http-verb="put"
    class="credits-modal-form-container"
    @onRequestSuccess="handleRequestSuccess"
  >
    <template #fields>
      <input-number
        form-id="restaurants-modal-form"
        model-name="credits-added"
        :label="$_tr('amount')"
        :rules="['required']"
        :steps="0.01"
        :use-asterisk="false"
        @onDataChange="({ value }) => (totalCredits = +credits + +value)"
      />

      <input-hidden
        form-id="restaurants-modal-form"
        model-name="fields"
        :default-value="['credits']"
      />

      <BaseText class="recap">
        {{
          $_tc('after', [totalCredits || 0], $_currentLang, totalCredits || 0)
        }}
      </BaseText>
    </template>
  </global-form>
</template>

<script>
import { BaseText } from 'inside-collection/atoms'

export default {
  name: 'credits-modal-form',
  $_i18nRootPath: 'customs.RESTAURANTS.MODALS.CREDITS.FORM',
  components: { BaseText },
  props: {
    userUuid: {
      type: String,
      required: true
    },
    credits: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      totalCredits: this.credits
    }
  },
  computed: {
    endpoint() {
      return `content/users/${this.userUuid}`
    }
  },
  methods: {
    formatData(data) {
      return {
        ...data,
        credits: this.totalCredits
      }
    },
    async handleRequestSuccess(res) {
      const { credits } = await res.json()
      this.totalCredits = credits
    }
  }
}
</script>

<style lang="scss">
.credits-modal-form-container {
  .recap {
    margin-top: calc(var(--spacing-m) + var(--spacing-s));
  }
}
</style>
