import { defineComponent, ref, watch } from 'vue';
import {
  getEditorEmits,
  getInputNumberProps,
  useNamespace,
} from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/editor/ibiz-input-number/ibiz-input-number.scss';

export const IBizInputNumber = defineComponent({
  name: 'IBizInputNumber',
  props: getInputNumberProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('input-number');

    const c = props.controller;

    const currentVal = ref<number | null | string>('');

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          const number = Number(newVal);
          currentVal.value = Number.isNaN(number) ? '' : number;
        }
      },
      { immediate: true },
    );

    const handleChange = (e: number | null) => {
      emit('change', e);
    };

    const inputRef = ref();

    if (props.autoFocus) {
      watch(inputRef, newVal => {
        if (newVal) {
          const input = newVal.$el.getElementsByTagName('input')[0];
          input.focus();
        }
      });
    }

    return {
      ns,
      c,
      currentVal,
      handleChange,
      inputRef,
    };
  },
  render() {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {this.readonly ? (
          this.currentVal
        ) : (
          <i-input-number
            ref='inputRef'
            value={this.currentVal}
            placeholder={this.c.placeHolder}
            precision={this.c.model.precision}
            disabled={this.disabled}
            on-on-change={this.handleChange}
          >
            {this.c.model.unitName && (
              <i class={this.ns.e('unit')} slot='suffix'>
                {this.c.model.unitName}
              </i>
            )}
          </i-input-number>
        )}
      </div>
    );
  },
});
