<template>
  <div :class="{ 'field-text-right': alignRight.includes(field.type), 'field-edit-render': true, 'field-container': true }">
    <label v-if="displayLabel">{{ field.title }}</label>
    <input v-if="field.type === 'boolean'" type="checkbox" v-model="internalValue" @change="save" />
    <inputSelect v-else-if="field.type === 'select'" v-model="internalValue" :options="field.options.map(o => ({ name: o.title, value: o.id }))" @input="save" />
    <input v-else :type="field.type" :placeholder="field.title" v-model="internalValue" :class="{ 'form-control': true, 'field': true }" @change="save" />
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'
import { keyValueTableFields } from '@/types'
import { inputSelect } from '@/index'
import { alignRight, convertValueToType } from './utils'

export default defineComponent({
  components: {
    inputSelect
  },
  props: {
    field: {
      type: Object as PropType<typeof keyValueTableFields[number]>,
      required: true,
    },
    value: {
      type: [String, Number, Boolean, Object],
      required: false,
    },
    displayLabel: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      internalValue: '' as string | number | boolean | object,
      alignRight,
    }
  },
  watch: {
    value: {
      handler(newVal) {
        if (typeof newVal === 'object' && newVal && Object.keys(newVal).length === 0) { 
          newVal = undefined
        }

        if (this.field.type === 'select' && newVal === undefined) {
          this.internalValue = this.field.options?.[0]?.id || ''
          this.$emit('input', this.internalValue)
        } else if (newVal === undefined) {
          this.internalValue = ''
          this.$emit('input', this.internalValue)
        } else {
          this.internalValue = JSON.parse(JSON.stringify(newVal))
        }
      },
      immediate: true,
    },
  },
  methods: {
    save() {
      this.$emit('input', convertValueToType(this.internalValue, this.field.type))
    },
  },
})
</script>

<style lang="scss" scoped>
.field-container {
  label {
    font-size: .75em;
    margin-bottom: 0;
    display: block;
    text-align: right;
  }
  .field {
    width: 100%;
  }
}

.field-text-right {
  input, select {
    text-align: right;
  }
}
</style> 