import type { PropType } from 'vue';
import { defineComponent, ref, computed, toRef, reactive, watch, onMounted } from 'vue'
import type { IText } from 'model';
import { IOperators, ISize } from 'model'

import { useI18n } from 'vue-i18n'
import { useQuasar } from 'quasar'

import { tools } from '@tools'

import { costanti } from '@costanti'

import { CMySize } from '@src/components/CMySize'
import { CMySlider } from '@src/components/CMySlider'
import { CMyFieldRec } from '@src/components/CMyFieldRec'

import { shared_consts } from '@src/common/shared_vuejs'

export default defineComponent({
  name: 'CMyText',
  emits: ['update:modelValue', 'modifElem', 'saveFieldElem',],
  components: { CMySlider, CMyFieldRec, CMySize },
  props: {
    modelValue: {
      type: Object as PropType<IText>,
      required: true,
    },
    label: {
      type: String,
      required: true,
    },
    disable: {
      type: Boolean,
      required: false,
      default: false,
    },
    show_maxlength: {
      type: Boolean,
      required: false,
      default: true,
    },
    show_dimensioni: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n()

    const internalModel = reactive({ ...props.modelValue })

    function modifElem() {
      // console.log('modifElem')
      emit('update:modelValue', { ...internalModel });
      emit('modifElem', null);
    }
    function update_col() {
      // console.log('update_col')
      emit('update:modelValue', { ...internalModel });
      emit('modifElem', null);
    }

    function saveFieldElem() {
      emit('update:modelValue', { ...internalModel });
      emit('saveFieldElem', null);
    }

    // Sincronizzare i cambiamenti esterni con internalModel quando props cambiano
    watch(() => props.modelValue, (newModel: any) => {
      Object.assign(internalModel, newModel);

    }, { immediate: true });

    function mounted() {
      if (!internalModel.font) {
        internalModel.font = {
          line_height: 1,
          posiz_text: 0,
          perc_text: '',
          name: '',
          size: '14px',
        }
      }
      if (!internalModel.font?.perc_text) {
        internalModel.font!.perc_text = ''
      }
      if (!internalModel.maxlength) {
        internalModel.maxlength = 0
      }
    }

    onMounted(mounted)

    return {
      t,
      shared_consts,
      internalModel,
      modifElem,
      tools,
      costanti,
      saveFieldElem,
      update_col,
    }
  }
})
