<template>
  <DefaultField :field="currentField" :errors="errors">
    <template #field>
        <div class="md:flex md:flex-row" v-for="(item, index) in items" :key="generator">
            <div class="w-full px-1 md:w-1/2">
                <div class="flex relative w-full">
                    <select
                        class="w-full block form-control form-input form-control-bordered"
                        v-model="item.key"
                        @change="optionSelected(item.key)"
                        :disabled="item.key !== ''"
                        required
                    >
                        <option value="" disabled>Select</option>
                        <option v-for="option in item.availableOptions" :key="option" :value="option.value">{{ option.label }}</option>
                    </select>

                    <svg class="flex-shrink-0 pointer-events-none form-select-arrow" xmlns="http://www.w3.org/2000/svg" width="10" height="6" viewBox="0 0 10 6">
                        <path class="fill-current" d="M8.292893.292893c.390525-.390524 1.023689-.390524 1.414214 0 .390524.390525.390524 1.023689 0 1.414214l-4 4c-.390525.390524-1.023689.390524-1.414214 0l-4-4c-.390524-.390525-.390524-1.023689 0-1.414214.390525-.390524 1.023689-.390524 1.414214 0L5 3.585786 8.292893.292893z"></path>
                    </svg>
                </div>
            </div>
            <div class="w-full px-1 md:w-1/2">
                <input
                    type="number"
                    v-model="item.value"
                    class="w-full form-control form-input form-input-bordered"
                />
            </div>
            <IconButton
                @click="removeItem(index)"
                class="ml-auto"
                iconType="trash"
                solid
                small
              />
        </div>

    <InvertedButton type="button" @click="addItem()" v-if="addButtonVisibility">
        <span>Add</span>
    </InvertedButton>

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

<script>
import { DependentFormField, HandlesValidationErrors } from 'laravel-nova'

export default {
    mixins: [DependentFormField, HandlesValidationErrors],
    props: ['resourceName', 'resourceId', 'field'],
    data: () => ({
        generator: 0,
        items: [],
        options: [],
        selectedValues: [],
        addButtonVisibility: true,
    }),
    methods: {
        /**
         * Fill the given FormData object with the field's internal value.
         */
        fill(formData) {
            this.items.forEach((item, index) => {
                if (item.key && item.value) {
                    formData.append(`${this.fieldAttribute}[${item.key}]`, item.value)
                }
            })
        },

        /**
         * Add item
         */
        addItem(key = '', value = '') {
            this.items.push({
                id: this.generator++,
                key: key,
                value: value,
                availableOptions: this.options.filter(option => ! this.selectedValues.includes(option.value))
            })

            this.addButtonVisibility = false
        },

        /**
         * Remove item
         */
        removeItem(index) {
            this.selectedValues = this.selectedValues.filter(item => item !== this.items[index].key)
            this.items.splice(index, 1)

            this.checkAddButtonVisibility()
        },

        /**
         * Option Selected
         */
        optionSelected(value) {
            this.selectedValues.push(value)

            this.checkAddButtonVisibility()
        },

        /**
         * Check Add Button Visibility
         */
        checkAddButtonVisibility() {
            if (this.selectedValues.length === this.options.length) {
                return
            }

            this.addButtonVisibility = true
        },
    },

    mounted() {
        this.options = Object.values(this.currentField.options)

        if (this.currentField.value && this.currentField.value.length > 0) {
            Array.from(this.currentField.value).forEach(value => {
                this.addItem(value.id, value.pivot.stock)
                this.optionSelected(value.id)
            })
        } else {
            this.addItem()
        }
    }
}
</script>
