import { defineComponent, ref, toRef, watch } from 'vue'
import { tools } from '@src/store/Modules/tools'

import { useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { toolsext } from '@store/Modules/toolsext'

export default defineComponent({
  name: 'CInput',
  emits: ['update:modelValue', 'savedb'],
  props: {
    modelValue: {
      type: [Number, String, null],
      required: true
    },
    label: {
      type: String,
      required: true,
      default: '',
    },
    copy: {
      type: Boolean,
      required: false,
      default: false,
    },
    dense: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  components: {},
  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n();

    const draftValue = ref(props.modelValue)
    const editing = ref(false)

    watch(toRef(props, 'modelValue'), (newVal) => {
      draftValue.value = newVal;
    })

    function copytoclip() {
      tools.copyStringToClipboard($q, draftValue.value.toString(), true)
    }

    // Abilita la modalità modifica al focus o all'input
    const onFocus = () => {
      // editing.value = true;
    }

    const onInputChange = () => {
      if (draftValue.value !== props.modelValue) {
        editing.value = true
      }
    }

    // Disabilita le frecce (ArrowUp e ArrowDown)
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
        event.preventDefault();
      }
      if (event.key === 'Enter') {
        confirmUpdate();
      }
    }

    // Conferma la modifica: emette l'evento per aggiornare il valore e chiama savedb
    const confirmUpdate = () => {
      if (draftValue.value !== props.modelValue) {
        emit('update:modelValue', draftValue.value);
        emit('savedb', draftValue.value);
      }
      editing.value = false
    }

    // Annulla la modifica: ripristina il valore originale e nasconde i bottoni
    const cancelUpdate = () => {
      draftValue.value = props.modelValue;
      editing.value = false;
    }

    return {
      tools,
      toolsext,
      copytoclip,
      draftValue,
      editing,
      onFocus,
      onInputChange,
      onKeyDown,
      confirmUpdate,
      cancelUpdate,
      t,
    }
  },
})
