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