<template>
  <DefaultField
    :field="currentField"
    :errors="errors"
    :show-help-text="showHelpText"
    :full-width-content="fullWidthContent"
  >
    <template #field>
      <inline-resource-table
        :resourceName="currentField.relatedResourceURI"
        :resources="resources"
        :singularName="currentField.singularLabel"
        @delete="deleteResources"
       />

      <CreateRelationButton
        v-tooltip="__('Create :resource', { resource: currentField.singularLabel })"
        @click="openRelationModal"
        :dusk="`${currentField.attribute}-inline-create`"
        />

        <CreateRelationModal
          :show="relationModalOpen"
          @set-resource="handleSetResource"
          @create-cancelled="closeRelationModal"
          size="7xl"
          :resource-name="currentField.relatedResourceURI"
          :resource-id="resourceId"
          :via-relationship="currentField.relationshipType"
          :via-resource="currentField.relatedResourceURI"
          :via-resource-id="viaResourceId"
        />

      <p v-if="hasError" class="my-2 text-danger">
        {{ firstError }}
      </p>
    </template>
  </DefaultField>
</template>

<script>
import { DependentFormField, HandlesValidationErrors } from 'laravel-nova'
import InlineResourceTable from '../DataTables/InlineResourceTable.vue'

export default {
  mixins: [DependentFormField, HandlesValidationErrors],

  props: ['resourceName', 'resourceId', 'field'],

  components: {
    'inline-resource-table': InlineResourceTable
  },

  data: () => ({
    relationModalOpen: false,
    viaResourceId: null,
    resources: [],
    createdResourceIds: [],
  }),

  methods: {
    /*
     * Set the initial, internal value for the field.
     */
    setInitialValue() {
      this.value = this.field.value || ''
    },

    /**
     * Open the relation modal
     */
    openRelationModal() {
      Nova.$emit('create-relation-modal-opened')
      this.relationModalOpen = true
    },

    /**
     * Close the relation modal
     */
    closeRelationModal() {
      this.relationModalOpen = false
      Nova.$emit('create-relation-modal-closed') 
    },

    /**
     * Handle setting the selected resource
     * @param  int options.id
     */
    handleSetResource({ id }) {
      this.closeRelationModal()

      this.createdResourceIds.push(id)

      this.fetchResources()
    },

    fetchResources() {
      Nova.request().get(`/nova-api/product-variants?ids=${this.createdResourceIds.join()}`).then(response => {
        this.resources = response.data.resources
      })
    },

    /**
     * Fill the given FormData object with the field's internal value.
     */
    fill(formData) {
      formData.append(this.fieldAttribute, this.createdResourceIds || [])
    },
  },

  mounted() {
  }
}
</script>
