<template>
  <div class="otp-wrapper">
    <input
      v-for="(item, index) in length"
      :key="index"
      ref="inputs"
      type="text"
      inputmode="numeric"
      maxlength="1"
      class="otp-input"
      v-model="codes[index]"
      @input="handleInput(index)"
      @keydown.backspace="handleBackspace(index)"
      @paste="handlePaste"
    />
  </div>
</template>

<script>
export default {
  props: {
    length: {
      type: Number,
      default: 9,
    },
    value: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      codes: Array(this.length).fill(''),
    };
  },
  methods: {
    handleInput(index) {
      const value = this.codes[index];

      // Chỉ cho nhập số
      if (!/^[0-9a-zA-Z]?$/.test(value)) {
        this.codes[index] = '';
        return;
      }

      // Tự nhảy sang ô tiếp theo
      if (value && index < this.length - 1) {
        this.$refs.inputs[index + 1].focus();
      }

      this.emitValue();
    },

    handleBackspace(index) {
      if (!this.codes[index] && index > 0) {
        this.$refs.inputs[index - 1].focus();
      }
    },

    handlePaste(event) {
      event.preventDefault();

      const paste = event.clipboardData.getData('text').trim();
      if (!paste) return;

      const values = paste
        .replace(/[^0-9a-zA-Z]/g, '')
        .slice(0, this.length)
        .split('');

      this.codes = Array(this.length).fill('');

      values.forEach((char, i) => {
        this.codes[i] = char;
      });

      this.$nextTick(() => {
        const index = Math.min(values.length, this.length - 1);
        this.$refs.inputs[index]?.focus();
      });

      this.emitValue();
    },

    emitValue() {
      const code = this.codes.join('');
      this.$emit('input', code);
    },
  },
};
</script>

<style lang="scss">
.otp-wrapper {
  display: flex;
  gap: 10px;
  justify-content: center;

  .otp-input {
    width: 42px;
    height: 48px;
    text-align: center;
    font-size: 18px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    outline: none;
    transition: all 0.2s;

    &:focus {
      border-color: #16a34a;
      box-shadow: 0 0 0 2px rgba(22, 163, 74, 0.2);
    }
  }
}
</style>
