import { ref as a, watch as y, inject as h, computed as j, onMounted as k, onUnmounted as A } from "vue";
import { injectFormGroupKey as R, injectFormKey as O } from "./keys.js";
const G = (r, { focus: I, emit: n, withListeners: b = !0 }) => {
  const s = a(!0), o = a(r.error), F = a(r.hideFooter), V = r.name ? r.name : (Math.random() + 1).toString(36).substring(7), i = a(V);
  y(() => r.error, (e) => {
    o.value = e;
  }), y(() => r.name, (e) => {
    e && (i.value = e);
  });
  const t = h(R, {
    registerInputGroup: () => {
    },
    unregisterInputGroup: () => {
    },
    setValue: () => {
    },
    isInsideFormGroup: !1,
    value: void 0
  });
  t.isInsideFormGroup && (F.value = !0);
  const m = h(O, {
    registerInput: () => {
    },
    unregisterInput: () => {
    },
    isInsideForm: !1
  }), S = () => {
    o.value = "", s.value = !0, n("update:modelValue", "");
  }, v = (e) => {
    o.value = e;
  }, c = (e) => {
    e = e || r.modelValue, s.value = !1;
    for (let g = 0; g < r.rules.length; g++) {
      const u = r.rules[g];
      let l = !0;
      if (typeof u == "function")
        l = u(e);
      else if (Array.isArray(u) && u.length === 2) {
        const { 0: d, 1: p } = u;
        l = d(e, p);
      } else {
        const d = u.fn, { options: p } = u;
        l = d(e, p);
      }
      if (l !== !0)
        return o.value = l, !1;
    }
    return o.value = "", !0;
  }, f = a(!1), B = b ? j(() => ({
    focus: (e) => {
      f.value = !0, n("focus", e);
    },
    blur: (e) => {
      f.value = !1, n("blur", e);
    },
    input: (e) => {
      r.validateOnInput && !s.value && c(e.target.value), n("update:modelValue", e.target.value), n("input", e);
    },
    change: (e) => n("change", e)
  })) : {
    focus: () => {
    },
    blur: () => {
    },
    input: () => {
    },
    change: () => {
    }
  };
  return k(() => {
    t.isInsideFormGroup ? t.registerInputGroup(i.value, I) : r.skipFormRegistry || m.registerInput(i.value, I, c, v);
  }), A(() => {
    t.isInsideFormGroup ? t.unregisterInputGroup(i.value) : r.skipFormRegistry || m.unregisterInput(i.value);
  }), {
    isFirstValidation: s,
    errorInternal: o,
    hideFooterInternal: F,
    isFocused: f,
    isInsideForm: r.skipFormRegistry ? !1 : m.isInsideForm,
    isInsideFormGroup: t.isInsideFormGroup,
    inputListeners: B,
    formGroup: t,
    reset: S,
    validate: c,
    setError: v
  };
};
G.emits = (r = !0) => r ? ["update:modelValue", "blur", "focus", "input", "change"] : ["update:modelValue"];
G.props = () => ({
  modelValue: {
    type: [String, Number, Boolean, Object, Array],
    default: void 0
  },
  id: String,
  name: String,
  readonly: Boolean,
  required: Boolean,
  validateOnInput: {
    type: Boolean,
    default: !0
  },
  label: String,
  helper: String,
  error: String,
  hideFooter: Boolean,
  rules: {
    type: Array,
    default: () => []
  },
  tooltip: String,
  skipFormRegistry: Boolean
});
export {
  G as useInputtable
};
