<template>
  <div @click="emit('click')" class="input text" :class="{ suffix: $slots.icon || maxlength, disabled, right, 'pre-suffix': $slots.preIcon }" ref="textRef">
    <template v-if="type === 'password'">
      <div class="is-hidden">
        <input type="text" class="is-hidden" />
        <input type="password" autocomplete="off" class="is-hidden" />
      </div>
    </template>

    <span v-if="$slots.preIcon" class="pre-icon">
      <slot name="preIcon" />
    </span>
    <input
      class="ui-text"
      :class="{ icon: $slots.icon }"
      :type="type"
      :value="modelValue"
      autocomplete="off"
      @input="inputHandler"
      :placeholder="props.placeholder"
      :readonly="readonly"
      :maxlength="props.maxlength"
      @focus="emit('focus')"
      @blur="emit('blur')"
      ref="inputRef"
      v-bind="other"
    />
    <span v-if="$slots.icon || props.maxlength" class="retouch">
      <slot name="icon" />
      <span v-if="props.maxlength" class="len">
        <span>{{ modelValue.length }}</span> / {{ maxlength }}
      </span>
    </span>
    <slot />
  </div>
</template>

<script setup>
import { textPropsDesc } from "./state";
import { defineProps, defineEmits, defineExpose, nextTick, ref } from "vue";
const props = defineProps({
  type: {
    type: String,
    default: "text",
  },
  ...textPropsDesc,
});
const emit = defineEmits(["update:modelValue", "focus", "blur", "click"]);
const test = () => {
  emit("focus");
};
const textRef = ref(null);
const inputRef = ref(null);

const inputHandler = (ev) => {
  emit("update:modelValue", ev.target.value);
  nextTick(() => {
    if (ev.target.value !== props.modelValue.toString()) {
      ev.target.value = props.modelValue.toString();
    }
  });
};

defineExpose({
  root: textRef,
  input: inputRef,
});
</script>

<style lang="scss" scoped>
.text {
  width: 250px;
  height: 40px;
  background: #fffef6;
  border-radius: 50px;
  border: 1px solid #999999;
  position: relative;
  input {
    color: #999999;
    height: 100%;
    padding: 0 20px;
    border-radius: 4px;
    border: 1px solid none;
    transition: border 0.3s ease;
    width: 100%;
    cursor: pointer;
  }

  &.pre-suffix {
    input {
      padding-left: 30px;
    }
    .pre-icon {
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  &.right input {
    text-align: right;
  }

  &.suffix {
    input {
      padding-right: 60px;
    }
    .retouch {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      z-index: 10;
      cursor: pointer;
    }

    .len {
      font-size: var(--small-size);
      color: rgba(var(--colors-primary-fill), 1);

      span {
        color: var(--colors-primary-base);
      }
    }
  }

  &.ready {
    .retouch,
    input {
      transition: all 0.1s linear;
    }
  }
}
</style>
