<template>
  <div
    :class="{
      'mm-ghost-input--disabled': disabled,
      'mm-ghost-input--readonly': readonly,
    }"
    class="mm-ghost-input">
    <span
      v-if="form === 'text'"
      class="mm-ghost-input-text-wrapper">
      <span
        v-if="!localValue && textPlaceholder"
        class="mm-ghost-input-text-placeholder">
        {{ textPlaceholder }}
      </span>
      <span
        v-else
        :title="localValue">
        {{ localValue }}
      </span>

      <span
        class="mm-ghost-input-switch"
        @click="switchForm('input')">
        <slot name="switch">
          <ui-icon
            name="edit"
            size="14px"></ui-icon>
        </slot>
      </span>
    </span>
    <ui-input
      v-if="form === 'input'"
      ref="input"
      v-model="localValue"
      :disabled="disabled"
      :readonly="readonly"
      :name="name"
      v-bind="$attrs"
      @blur="switchForm('text')"></ui-input>
  </div>
</template>

<script>
import Icon from "../icon"
import Input from "../input"
import input from "../../mixins/input"

export default {
  name: "mm-ghost-input",
  components: {
    "ui-icon": Icon,
    "ui-input": Input,
  },
  mixins: [input],
  inheritAttrs: false,
  props: {
    value: String,
    textPlaceholder: String,
    disabled: Boolean,
  },
  data() {
    return {
      localValue: "",
      form: "text",
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.localValue = val
      },
    },
    localValue(val) {
      this.$emit("input", val)
    },
  },
  methods: {
    switchForm(form) {
      if (this.disabled || this.readonly) {
        return
      }

      this.form = form

      if (form === "input") {
        this.$nextTick(() => {
          this.$refs.input.focus()
        })
      }

      if (form === "text") {
        this.$emit("blur", this.localValue)
      }
    },
  },
}
</script>
