<script setup>
import { computed } from "vue";
import { numberValue, errorMessages } from "./model.js";
const props = defineProps({
  form: Object,
  name: String,
  label: String,
  type: { default: "text" },
  help: String,
  options: Array,
  validators: Object,
  uid: String,
});
const id = computed(
  () => props.uid || "field-" + props.name.replace(/[^\w-]/g, "-"),
);
function change(field, event) {
  field.setMeta((m) => ({
    ...m,
    errorMap: { ...m.errorMap, onServer: undefined },
  }));
  field.handleChange(
    props.type === "checkbox"
      ? event.target.checked
      : props.type === "number"
        ? numberValue(event.target.value)
        : event.target.value,
  );
}
</script>
<template>
  <component :is="form.Field" :name="name" :validators="validators"
    ><template #default="{ field }"
      ><div class="field-block">
        <label :for="id" class="form-label">{{ label }}</label>
        <select
          v-if="options"
          :id="id"
          :name="name"
          class="form-select"
          :value="field.state.value"
          @change="change(field, $event)"
          @blur="field.handleBlur"
          :aria-invalid="field.state.meta.errors.length > 0"
          :aria-describedby="id + '-help ' + id + '-error'"
        >
          <option
            v-for="o in options"
            :key="o.value ?? o"
            :value="o.value ?? o"
          >
            {{ o.label ?? o }}
          </option>
        </select>
        <input
          v-else
          :id="id"
          :name="name"
          :type="type"
          :value="field.state.value"
          :checked="type === 'checkbox' ? field.state.value : undefined"
          :class="type === 'checkbox' ? 'form-check-input' : 'form-control'"
          @input="change(field, $event)"
          @blur="field.handleBlur"
          :aria-invalid="field.state.meta.errors.length > 0"
          :aria-describedby="id + '-help ' + id + '-error'"
          :step="type === 'number' ? 'any' : undefined"
          autocomplete="off"
        />
        <small :id="id + '-help'" class="field-help">{{ help }}</small><span
          v-if="field.state.meta.isValidating"
          class="checking"
          role="status"
          >Проверяем…</span
        >
        <p
          :id="id + '-error'"
          class="field-error"
          :role="field.state.meta.errors.length ? 'alert' : undefined"
        >
          {{ errorMessages(field.state.meta.errors).join(" · ") }}
        </p>
      </div></template
    ></component
  >
</template>
